SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating full text catalogs'
GO
CREATE FULLTEXT CATALOG [ProcessDefinitionFtIndex]
WITH ACCENT_SENSITIVITY = ON
AUTHORIZATION [dbo]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
BEGIN TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Repository]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Repository]
(
[RepositoryId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryName] [nvarchar] (256) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Repository] on [dbo].[ProcessDefinition_Repository]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Repository] ADD CONSTRAINT [PK_ProcessDefinition_Repository] PRIMARY KEY CLUSTERED  ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Repository_RepositoryName] on [dbo].[ProcessDefinition_Repository]'
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_ProcessDefinition_Repository_RepositoryName] ON [dbo].[ProcessDefinition_Repository] ([RepositoryName])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Member]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Member]
(
[MemberId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[MemberRole] [int] NOT NULL,
[UserAssigned] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_Member_UserAdded] DEFAULT ((1))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Member] on [dbo].[ProcessDefinition_Member]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Member] ADD CONSTRAINT [PK_ProcessDefinition_Member] PRIMARY KEY CLUSTERED  ([MemberId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Member_RepositoryId] on [dbo].[ProcessDefinition_Member]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Member_RepositoryId] ON [dbo].[ProcessDefinition_Member] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Member_UserId] on [dbo].[ProcessDefinition_Member]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Member_UserId] ON [dbo].[ProcessDefinition_Member] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUserMemberRole]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetUserMemberRole] 
	@userId int,
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_Member.MemberRole
	FROM         ProcessDefinition_Member INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND (ProcessDefinition_Member.UserId = @userId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_AssignedTag]'
GO
CREATE TABLE [dbo].[Notes_AssignedTag]
(
[AssignedTagId] [int] NOT NULL IDENTITY(1, 1),
[TagId] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[AssignedByForeignId] [int] NOT NULL,
[AssignedByForeignType] [int] NOT NULL,
[AssignedDt] [datetime] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Notes_Assigned] on [dbo].[Notes_AssignedTag]'
GO
ALTER TABLE [dbo].[Notes_AssignedTag] ADD CONSTRAINT [PK_Notes_Assigned] PRIMARY KEY CLUSTERED  ([AssignedTagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_AssignedTag_TagId] on [dbo].[Notes_AssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_AssignedTag_TagId] ON [dbo].[Notes_AssignedTag] ([TagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_AssignedTag_ForeignId] on [dbo].[Notes_AssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_AssignedTag_ForeignId] ON [dbo].[Notes_AssignedTag] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_AssignedTag_ForeignType] on [dbo].[Notes_AssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_AssignedTag_ForeignType] ON [dbo].[Notes_AssignedTag] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_AssignedTag_AssignedByForeignId] on [dbo].[Notes_AssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_AssignedTag_AssignedByForeignId] ON [dbo].[Notes_AssignedTag] ([AssignedByForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_DeleteAssignedTags]'
GO
CREATE PROCEDURE [dbo].[Notes_DeleteAssignedTags]
		@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DELETE FROM Notes_AssignedTag WHERE ForeignId=@foreignId AND ForeignType=@foreignType
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_LicenseUserHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_LicenseUserHistory]
(
[LicenseUserId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[LicenseId] [int] NOT NULL,
[Expiry] [datetime] NOT NULL,
[Session] [varchar] (32) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_LicenseUser]'
GO
CREATE TABLE [dbo].[ProcessDefinition_LicenseUser]
(
[LicenseUserId] [int] NOT NULL IDENTITY(1, 1),
[UserId] [int] NOT NULL,
[LicenseId] [int] NOT NULL,
[Expiry] [datetime] NOT NULL,
[Session] [varchar] (32) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_LicenseUser] on [dbo].[ProcessDefinition_LicenseUser]'
GO
ALTER TABLE [dbo].[ProcessDefinition_LicenseUser] ADD CONSTRAINT [PK_ProcessDefinition_LicenseUser] PRIMARY KEY CLUSTERED  ([LicenseUserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CleanupUserLicenseSessions]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_CleanupUserLicenseSessions] 
	@userId int,
	@LicenseId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @output TABLE (LicenseUserId int, UserId int, LicenseId int, Expiry datetime, Session varchar(32))

		DELETE FROM ProcessDefinition_LicenseUser 
	OUTPUT DELETED.LicenseUserId, DELETED.UserId, DELETED.LicenseId, DELETED.Expiry, DELETED.Session INTO @output
	WHERE ((UserId=@userId) AND ((@LicenseId IS NULL) OR LicenseId!=@LicenseId))
		 OR Expiry < GetDate()

	INSERT INTO dbo.ProcessDefinition_LicenseUserHistory(LicenseUserId,  UserId, LicenseId, Expiry, Session)
	SELECT LicenseUserId, UserId, LicenseId, Expiry, Session
		FROM @output

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_CreateAssignedTagWithTagId]'
GO
CREATE PROCEDURE [dbo].[Notes_CreateAssignedTagWithTagId]
	@foreignId int,
	@foreignType int,
	@AssignedByForeignId int,
	@AssignedByForeignType int,
	@tagId nvarchar(100),
	@AssignedTagId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT @AssignedTagId=AssignedTagId FROM Notes_AssignedTag WHERE TagId=@tagId AND ForeignId=@foreignId AND ForeignType=@foreignType

	IF(@AssignedTagId IS NULL)
	BEGIN
		INSERT INTO Notes_AssignedTag
						(TagId, ForeignId, ForeignType, AssignedByForeignId, AssignedByForeignType, AssignedDt)
		VALUES     (@tagId,@foreignId,@foreignType,@AssignedByForeignId,@AssignedByForeignType, GETUTCDATE())

		SET @AssignedTagId=Scope_Identity()
	END

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProcessHistory]
(
[ProcessHistoryId] [int] NOT NULL IDENTITY(1, 1),
[ProcessId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[DateCreated] [datetime] NOT NULL,
[ProcessDescription] [nvarchar] (max) NULL,
[ProcessTitle] [nvarchar] (256) NULL,
[IsPublished] [bit] NOT NULL,
[DateUpdated] [datetime] NULL,
[DefaultTags] [int] NULL,
[PrettyPostTitle] [nvarchar] (256) NOT NULL,
[DescriptionSnippet] [nvarchar] (1024) NULL,
[MajorVersion] [int] NOT NULL,
[MinorVersion] [int] NOT NULL,
[UserId] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessHistory_UserId] DEFAULT ((0)),
[ProcessTypeId] [int] NULL,
[DateFrozen] [datetime] NULL,
[IsFrozenVersion] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessHistory_IsFrozenVersion] DEFAULT ((0)),
[IsLatestVersion] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessHistory_IsLatestVersion] DEFAULT ((0)),
[AltGroup] [nvarchar] (256) NULL,
[RelationshipGraph] [nvarchar] (max) NULL,
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessHistory_IsDeleted] DEFAULT ((0)),
[StepDefinitionVersion] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessHistory_StepDefinitionVersion] DEFAULT ((1)),
[StepsSvg] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefintion_ProcessHistory] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProcessHistory] ADD CONSTRAINT [PK_ProcessDefintion_ProcessHistory] PRIMARY KEY CLUSTERED  ([ProcessHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_ProcessId] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_ProcessId] ON [dbo].[ProcessDefinition_ProcessHistory] ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_ForeignType] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_ForeignType] ON [dbo].[ProcessDefinition_ProcessHistory] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_ForeignId] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_ForeignId] ON [dbo].[ProcessDefinition_ProcessHistory] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_MajorVersion] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_MajorVersion] ON [dbo].[ProcessDefinition_ProcessHistory] ([MajorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_MinorVersion] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_MinorVersion] ON [dbo].[ProcessDefinition_ProcessHistory] ([MinorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_UserId] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_UserId] ON [dbo].[ProcessDefinition_ProcessHistory] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessHistory_ProcessTypeId] on [dbo].[ProcessDefinition_ProcessHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessHistory_ProcessTypeId] ON [dbo].[ProcessDefinition_ProcessHistory] ([ProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessHistory]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessHistory] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessHistoryId, ProcessId, ForeignType, ForeignId, DateCreated, ProcessDescription, ProcessTitle, IsPublished, DateUpdated, DefaultTags, PrettyPostTitle, 
						  DescriptionSnippet, MajorVersion, MinorVersion, UserId, ProcessTypeId, DateFrozen, IsFrozenVersion, IsLatestVersion
	FROM         ProcessDefinition_ProcessHistory
	WHERE     (ProcessHistoryId = @processHistoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StepPredecessorHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_StepPredecessorHistory]
(
[StepPredecessorHistoryId] [int] NOT NULL IDENTITY(1, 1),
[StepPredecessorId] [int] NOT NULL,
[ParentProcessId] [int] NOT NULL,
[ProcessStepId] [int] NOT NULL,
[StepUId] [uniqueidentifier] NOT NULL,
[FromProcessStepId] [int] NOT NULL,
[FromStepUId] [uniqueidentifier] NOT NULL,
[PredecessorText] [nvarchar] (250) NULL,
[ProcessHistoryId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_StepPredecessorHistory] on [dbo].[ProcessDefinition_StepPredecessorHistory]'
GO
ALTER TABLE [dbo].[ProcessDefinition_StepPredecessorHistory] ADD CONSTRAINT [PK_ProcessDefinition_StepPredecessorHistory] PRIMARY KEY CLUSTERED  ([StepPredecessorHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetHistoryStepPredecessors]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetHistoryStepPredecessors] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;



	SELECT StepPredecessorHistoryId, StepPredecessorId, ParentProcessId, ProcessStepId, StepUId, FromProcessStepId, FromStepUId, PredecessorText, ProcessHistoryId
	FROM  ProcessDefinition_StepPredecessorHistory 
	WHERE (ProcessDefinition_StepPredecessorHistory.ProcessHistoryId = @processHistoryId)	
	



END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_DeleteAssignedTag]'
GO
CREATE PROCEDURE [dbo].[Notes_DeleteAssignedTag]
	@AssignedTagId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DELETE FROM Notes_AssignedTag
	WHERE     (AssignedTagId = @AssignedTagId)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTaskLink]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTaskLink]
(
[ProjectPlanTaskLinkId] [int] NOT NULL IDENTITY(1, 1),
[TaskId] [int] NOT NULL,
[LinksToProcessHistoryId] [int] NOT NULL,
[LinksToProcessId] [int] NOT NULL,
[ProcessLinkHistoryId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlanTaskLink] on [dbo].[ProcessDefinition_ProjectPlanTaskLink]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTaskLink] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlanTaskLink] PRIMARY KEY CLUSTERED  ([ProjectPlanTaskLinkId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]
(
[AssignedTaskId] [int] NOT NULL IDENTITY(1, 1),
[AssignedById] [int] NOT NULL,
[AssignedToId] [int] NOT NULL,
[TaskId] [int] NOT NULL,
[AssignmentNote] [nvarchar] (max) NOT NULL,
[AssignedDate] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_AssignedProcess_AssignedDate] DEFAULT (getutcdate()),
[IgnoredBy] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_AssignedProcess_IgnoredBy] DEFAULT ((0)),
[IgnoredTo] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_AssignedProcess_IgnoredTo] DEFAULT ((0)),
[GroupingGuid] [uniqueidentifier] NULL,
[ProjectId] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_AssignedProcess_ProjectId] DEFAULT ((0)),
[AssignedManually] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTaskAssignment_AssignedManually] DEFAULT ((1))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_AssignedProcess] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ADD CONSTRAINT [PK_ProcessDefinition_AssignedProcess] PRIMARY KEY CLUSTERED  ([AssignedTaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_AssignedProcess_AssignedById] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_AssignedProcess_AssignedById] ON [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ([AssignedById])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_AssignedProcess_AssignedToId] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_AssignedProcess_AssignedToId] ON [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ([AssignedToId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_AssignedProcess_ProcessId] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_AssignedProcess_ProcessId] ON [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ([TaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_AssignedProcess_GroupingGuid] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_AssignedProcess_GroupingGuid] ON [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ([GroupingGuid])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_AssignedProcess_ProjectId] on [dbo].[ProcessDefinition_ProjectPlanTaskAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_AssignedProcess_ProjectId] ON [dbo].[ProcessDefinition_ProjectPlanTaskAssignment] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTask]
(
[ProjectPlanTaskId] [int] NOT NULL IDENTITY(1, 1),
[TaskName] [nvarchar] (256) NOT NULL,
[ParentTaskId] [int] NULL,
[TaskGuid] [nvarchar] (50) NOT NULL,
[TaskProcessId] [int] NULL,
[TaskStepId] [int] NULL,
[TaskOptional] [bit] NOT NULL,
[TaskIterative] [bit] NOT NULL,
[TaskIsRemoved] [bit] NOT NULL,
[TaskBasedOnGuid] [nvarchar] (50) NULL,
[ProjectPlanId] [int] NOT NULL,
[TaskConcurrent] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_TaskConcurrent] DEFAULT ((0)),
[TaskNotes] [nvarchar] (max) NULL,
[TaskPosition] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_TaskPosition] DEFAULT ((0)),
[TaskType] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_TaskType] DEFAULT ((1)),
[ProcessHistoryId] [int] NULL,
[RemovalReason] [nvarchar] (max) NULL,
[EditorUserId] [int] NULL,
[EstimatedStartDate] [datetime] NULL,
[EstimatedEndDate] [datetime] NULL,
[ActualStartDate] [datetime] NULL,
[ActualEndDate] [datetime] NULL,
[CurrentStatus] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_CurrentStatus] DEFAULT ((1)),
[StatusNotes] [nvarchar] (max) NULL,
[TaskProgressPc] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_TaskProgressPc] DEFAULT ((0)),
[StartedUserId] [int] NULL,
[FinishedUserId] [int] NULL,
[DateUpdated] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanTask_DateUpdated] DEFAULT (getutcdate()),
[StepUpgradeHistory] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlanTask] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTask] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlanTask] PRIMARY KEY CLUSTERED  ([ProjectPlanTaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_ParentTaskId] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_ParentTaskId] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([ParentTaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_TaskGuid] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_TaskGuid] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([TaskGuid])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_TaskProcessId] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_TaskProcessId] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([TaskProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_TaskStepId] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_TaskStepId] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([TaskStepId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_TaskBasedOnGuid] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_TaskBasedOnGuid] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([TaskBasedOnGuid])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTask_ProjectPlanId] on [dbo].[ProcessDefinition_ProjectPlanTask]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTask_ProjectPlanId] ON [dbo].[ProcessDefinition_ProjectPlanTask] ([ProjectPlanId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Process]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Process]
(
[ProcessId] [int] NOT NULL IDENTITY(1, 1),
[ForeignType] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[DateCreated] [datetime] NOT NULL,
[ProcessDescription] [nvarchar] (max) NULL,
[ProcessTitle] [nvarchar] (256) NULL,
[IsPublished] [bit] NOT NULL,
[DateUpdated] [datetime] NULL,
[DefaultTags] [int] NULL CONSTRAINT [DF_ProcessDefintion_Process_DefaultTags] DEFAULT ((0)),
[PrettyPostTitle] [nvarchar] (256) NOT NULL,
[DescriptionSnippet] [nvarchar] (1024) NULL,
[MajorVersion] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_Process_MajorVersion] DEFAULT ((0)),
[MinorVersion] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_Process_MinorVersion] DEFAULT ((0)),
[UserId] [int] NOT NULL,
[ProcessTypeId] [int] NULL,
[DateFrozen] [datetime] NULL,
[AltGroup] [nvarchar] (256) NULL,
[ProcessUId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ProcessDefinition_Process_UniqueId] DEFAULT (newid()),
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_Process_IsDeleted] DEFAULT ((0)),
[RelationshipGraph] [nvarchar] (max) NULL,
[StepDefinitionVersion] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_Process_StepDefinitionVersion] DEFAULT ((1)),
[StepsSvg] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefintion_Process] on [dbo].[ProcessDefinition_Process]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Process] ADD CONSTRAINT [PK_ProcessDefintion_Process] PRIMARY KEY CLUSTERED  ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_ForeignType] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_ForeignType] ON [dbo].[ProcessDefinition_Process] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_ForeignId] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_ForeignId] ON [dbo].[ProcessDefinition_Process] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_MajorVersion] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_MajorVersion] ON [dbo].[ProcessDefinition_Process] ([MajorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_MinorVersion] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_MinorVersion] ON [dbo].[ProcessDefinition_Process] ([MinorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_UserId] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_UserId] ON [dbo].[ProcessDefinition_Process] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Process_ProcessTypeId] on [dbo].[ProcessDefinition_Process]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Process_ProcessTypeId] ON [dbo].[ProcessDefinition_Process] ([ProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_HasProcessAccess]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_HasProcessAccess] 
(
	@processId int,
	@userId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN

		DECLARE @RepositoryId int
	SELECT  @RepositoryId=RepositoryId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId 
	WHERE     (ProcessDefinition_Process.ProcessId = @processId)

	
	DECLARE @HasPostAccess bit

		IF(@processId IN ( 
		SELECT     ProcessDefinition_ProjectPlanTask.TaskProcessId AS ProcessId
		FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
							  ProcessDefinition_ProjectPlanTaskAssignment ON 
							  ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
		WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId)

		UNION

		SELECT     ProcessDefinition_ProjectPlanTaskLink.LinksToProcessId AS ProcessId
		FROM         ProcessDefinition_ProjectPlanTaskAssignment INNER JOIN
							  ProcessDefinition_ProjectPlanTaskLink ON ProcessDefinition_ProjectPlanTaskAssignment.TaskId = ProcessDefinition_ProjectPlanTaskLink.TaskId
		WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId)
		)
	)
	BEGIN

		SET @HasPostAccess=1

	END
	ELSE
	BEGIN

		DECLARE @MemberRole int
		SELECT     @MemberRole= MemberRole
		FROM         ProcessDefinition_Member
		WHERE     (UserId = @userId) AND (RepositoryId = @RepositoryId)

		IF(@MemberRole>=3)
		BEGIN
						SET @HasPostAccess=1
		END


	END


	RETURN  @HasPostAccess 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProcessLink]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProcessLink]
(
[ProcessLinkId] [int] NOT NULL IDENTITY(1, 1),
[ProcessId] [int] NOT NULL,
[SectionName] [nvarchar] (255) NULL,
[LinkUri] [nvarchar] (1024) NULL,
[LinksToProcessId] [int] NULL,
[FullLinkUri] [nvarchar] (1024) NOT NULL,
[LinkText] [nvarchar] (1024) NULL,
[LinkType] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessLink_LinkType] DEFAULT ((0)),
[LinkUid] [nvarchar] (50) NULL,
[SectionDirection] [nvarchar] (10) NULL,
[SectionMultiplicity] [nvarchar] (10) NULL,
[SectionType] [nvarchar] (128) NULL,
[SectionLinkTypeId] [int] NULL,
[ExcludedLinksToProcessId] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProcessLink] on [dbo].[ProcessDefinition_ProcessLink]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProcessLink] ADD CONSTRAINT [PK_ProcessDefinition_ProcessLink] PRIMARY KEY CLUSTERED  ([ProcessLinkId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessLink_ProcessId] on [dbo].[ProcessDefinition_ProcessLink]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessLink_ProcessId] ON [dbo].[ProcessDefinition_ProcessLink] ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessLink_LinksToProcessId] on [dbo].[ProcessDefinition_ProcessLink]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessLink_LinksToProcessId] ON [dbo].[ProcessDefinition_ProcessLink] ([LinksToProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkedProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkedProcesses] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
SELECT     ProcessDefinition_ProcessLink.ProcessLinkId, ProcessDefinition_ProcessLink.ProcessId, ProcessDefinition_ProcessLink.SectionName, 
                      ProcessDefinition_ProcessLink.LinkUri, ProcessDefinition_ProcessLink.FullLinkUri, ProcessDefinition_ProcessLink.LinkText, 
                      ProcessDefinition_Process.PrettyPostTitle, 
		ProcessDefinition_Process.ProcessTitle, ProcessTypeId, LinksToProcessId, LinkType, SectionDirection
FROM         ProcessDefinition_ProcessLink INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_ProcessLink.LinksToProcessId = ProcessDefinition_Process.ProcessId
WHERE     (ProcessDefinition_ProcessLink.ProcessId = @processId) AND IsDeleted = 0

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessCount]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessCount]
	@foreignType int,
	@foreignId int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @pCount int 

     SELECT @pCount=COUNT(ProcessId)
            FROM ProcessDefinition_Process
	WHERE 	ForeignType=@foreignType AND
            ForeignId=@foreignId

	SELECT @pCount AS PostCount

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_License]'
GO
CREATE TABLE [dbo].[ProcessDefinition_License]
(
[LicenseId] [int] NOT NULL IDENTITY(1, 1),
[Info] [nvarchar] (256) NOT NULL,
[Feature] [nvarchar] (5) NOT NULL,
[Count] [int] NOT NULL,
[ValidFrom] [datetime] NOT NULL,
[ValidTo] [datetime] NOT NULL,
[Validation] [nvarchar] (512) NOT NULL,
[ValidationCode] [nvarchar] (50) NOT NULL,
[IsDefault] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_License_IsDefault] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_License] on [dbo].[ProcessDefinition_License]'
GO
ALTER TABLE [dbo].[ProcessDefinition_License] ADD CONSTRAINT [PK_ProcessDefinition_License] PRIMARY KEY CLUSTERED  ([LicenseId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_User]'
GO
CREATE TABLE [dbo].[Account_User]
(
[UserId] [int] NOT NULL IDENTITY(1, 1),
[MemberId] [uniqueidentifier] NULL,
[UserType] [int] NOT NULL,
[DisplayName] [nvarchar] (100) NOT NULL,
[MemberEmailAddress] [nvarchar] (256) NULL,
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_Account_User_IsDeleted] DEFAULT ((0)),
[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_Account_User_DateCreated] DEFAULT (getutcdate()),
[CreatedByUserId] [int] NULL,
[Profile] [nvarchar] (max) NOT NULL CONSTRAINT [DF_Account_User_Profile] DEFAULT (''),
[LicenseId] [int] NULL CONSTRAINT [DF_Account_User_LicenseId] DEFAULT ((-1)),
[SendNotifications] [bit] NOT NULL CONSTRAINT [DF_Account_User_SendNotifications] DEFAULT ((1))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Account_User] on [dbo].[Account_User]'
GO
ALTER TABLE [dbo].[Account_User] ADD CONSTRAINT [PK_Account_User] PRIMARY KEY CLUSTERED  ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Account_User_MemberId] on [dbo].[Account_User]'
GO
CREATE NONCLUSTERED INDEX [IX_Account_User_MemberId] ON [dbo].[Account_User] ([MemberId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_LicenseUsage]'
GO
CREATE PROCEDURE [dbo].[Report_LicenseUsage] 
  
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     Account_User.DisplayName AS tf_UserName, 
		Account_User.MemberEmailAddress AS tf_EMail, 
		LicenseUsage.Expiry AS dtl_Expiry, 
		ProcessDefinition_License.Info, 
              ProcessDefinition_License.ValidFrom, 
		ProcessDefinition_License.ValidTo
FROM      (   
	SELECT UserId, LicenseId, Expiry FROM ProcessDefinition_LicenseUser 
		UNION
	SELECT UserId, LicenseId, Expiry FROM ProcessDefinition_LicenseUserHistory
	) AS LicenseUsage INNER JOIN
                      Account_User ON LicenseUsage.UserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_License ON LicenseUsage.LicenseId = ProcessDefinition_License.LicenseId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryId]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_GetRepositoryId] 
(
	@repositoryName nvarchar(256)
)
RETURNS int
WITH ENCRYPTION AS
BEGIN
		DECLARE @Result int

	
	SELECT     @Result = RepositoryId
	FROM         ProcessDefinition_Repository
	WHERE     (RepositoryName = @repositoryName)

		RETURN @Result

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllProcessHistories]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAllProcessHistories]
(
     @repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName) 

	SELECT ProcessHistoryId, ProcessDescription, ProcessId, IsLatestVersion, MajorVersion, MinorVersion, ProcessTitle
	FROM  ProcessDefinition_ProcessHistory
	WHERE (ForeignId = @RepositoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkedProcessesForUpdate]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkedProcessesForUpdate]
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	
	SELECT     LinkedProcesses.ProcessId, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.ProcessDescription, ProcessDefinition_Process.IsPublished, ProcessDefinition_Process.ProcessTypeId
	FROM         (SELECT     ProcessId
						   FROM          ProcessDefinition_ProcessLink
						   WHERE      (LinksToProcessId = @processId)
						   GROUP BY ProcessId) AS LinkedProcesses INNER JOIN
						  ProcessDefinition_Process ON LinkedProcesses.ProcessId = ProcessDefinition_Process.ProcessId

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_AlternativeGroups]'
GO
CREATE PROCEDURE [dbo].[Report_AlternativeGroups] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)


SELECT     ProcessDefinition_Process.ProcessTitle AS tf_Title,
ProcessDefinition_Process.AltGroup AS dd_AlternativeGroup, 
	'~/' + ProcessDefinition_Process.PrettyPostTitle AS link_Process
FROM         ProcessDefinition_Process 
WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId AND IsDeleted=0)
ORDER BY AltGroup, ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Project]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Project]
(
[ProjectId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[ProjectName] [nvarchar] (256) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Project] on [dbo].[ProcessDefinition_Project]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Project] ADD CONSTRAINT [PK_ProcessDefinition_Project] PRIMARY KEY CLUSTERED  ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Project_RepositoryId] on [dbo].[ProcessDefinition_Project]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Project_RepositoryId] ON [dbo].[ProcessDefinition_Project] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectByName]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectByName]
(
     @repositoryName nvarchar(256),	
     @ProjectName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

 	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

     SELECT RepositoryId,  ProjectName
		FROM ProcessDefinition_Project WHERE ProjectName LIKE @ProjectName AND RepositoryId=@RepositoryId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_PublishProcess]'
GO
CREATE TABLE [dbo].[ProcessDefinition_PublishProcess]
(
[PublishProcessId] [int] NOT NULL IDENTITY(1, 1),
[ProcessId] [int] NOT NULL,
[ProcessHistoryId] [int] NOT NULL,
[PublishId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Publish]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Publish]
(
[PublishId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[Title] [nvarchar] (128) NOT NULL,
[Description] [ntext] NULL,
[Version] [nvarchar] (128) NULL,
[PublishDate] [datetime] NOT NULL,
[UserId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectProcessVersion]
(
[ProjectPlanId] [int] NOT NULL,
[ProcessId] [int] NOT NULL,
[MajorVersion] [int] NOT NULL,
[MinorVersion] [int] NOT NULL,
[ProjectProcessId] [int] NOT NULL IDENTITY(1, 1),
[ProcessHistoryId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectProcessVersion] on [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectProcessVersion] ADD CONSTRAINT [PK_ProcessDefinition_ProjectProcessVersion] PRIMARY KEY CLUSTERED  ([ProjectProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessVersion_ProjectPlanId] on [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessVersion_ProjectPlanId] ON [dbo].[ProcessDefinition_ProjectProcessVersion] ([ProjectPlanId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessVersion_ProcessId] on [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessVersion_ProcessId] ON [dbo].[ProcessDefinition_ProjectProcessVersion] ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessVersion_MajorVersion] on [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessVersion_MajorVersion] ON [dbo].[ProcessDefinition_ProjectProcessVersion] ([MajorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessVersion_MinorVersion] on [dbo].[ProcessDefinition_ProjectProcessVersion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessVersion_MinorVersion] ON [dbo].[ProcessDefinition_ProjectProcessVersion] ([MinorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectProcessType]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectProcessType]
(
[ProjectProcessTypeId] [int] NOT NULL IDENTITY(1, 1),
[ProjectPlanId] [int] NOT NULL,
[ProcessTypeId] [int] NOT NULL,
[RepositoryId] [int] NOT NULL,
[ProcessTypeName] [nvarchar] (128) NOT NULL,
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectProcessType_IsDeleted] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectProcessType] on [dbo].[ProcessDefinition_ProjectProcessType]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectProcessType] ADD CONSTRAINT [PK_ProcessDefinition_ProjectProcessType] PRIMARY KEY CLUSTERED  ([ProjectProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessType_ProjectPlanId] on [dbo].[ProcessDefinition_ProjectProcessType]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessType_ProjectPlanId] ON [dbo].[ProcessDefinition_ProjectProcessType] ([ProjectPlanId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessType_ProcessTypeId] on [dbo].[ProcessDefinition_ProjectProcessType]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessType_ProcessTypeId] ON [dbo].[ProcessDefinition_ProjectProcessType] ([ProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectProcessType_RepositoryId] on [dbo].[ProcessDefinition_ProjectProcessType]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectProcessType_RepositoryId] ON [dbo].[ProcessDefinition_ProjectProcessType] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProcessType]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProcessType]
(
[ProcessTypeId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[ProcessTypeName] [nvarchar] (128) NOT NULL,
[ProcessTypeTemplate] [nvarchar] (max) NOT NULL,
[TypeUId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessType_UniqueId] DEFAULT (newid()),
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessType_IsDeleted] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProcessType] on [dbo].[ProcessDefinition_ProcessType]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProcessType] ADD CONSTRAINT [PK_ProcessDefinition_ProcessType] PRIMARY KEY CLUSTERED  ([ProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProcessType_RepositoryId] on [dbo].[ProcessDefinition_ProcessType]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProcessType_RepositoryId] ON [dbo].[ProcessDefinition_ProcessType] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesByTitle]'
GO
 

CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesByTitle]
(
     @repositoryName nvarchar(256),
     @PostTitle nvarchar(256),
	@projectId int, 	@TaskId int ,
	@UsePublished bit
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
     IF(@projectId IS NULL AND @TaskId IS NULL AND @UsePublished=1)
	BEGIN

	   DECLARE @lastPublishedId int
	   SELECT @lastPublishedId=MAX(PublishId)
	   FROM  ProcessDefinition_Publish
	   WHERE (RepositoryId = @RepositoryId)

	   SELECT ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, ProcessDefinition_ProcessHistory.ProcessId, 
			  ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, ProcessDefinition_ProcessHistory.ProcessTypeId, ProcessDefinition_ProcessType.ProcessTypeName, ProcessDefinition_ProcessHistory.DateFrozen, ProcessDefinition_ProcessHistory.AltGroup,
			  ProcessDefinition_ProcessHistory.ProcessHistoryId
	   FROM  ProcessDefinition_ProcessHistory INNER JOIN
			  ProcessDefinition_ProcessType ON ProcessDefinition_ProcessHistory.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId INNER JOIN
			  ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
	   WHERE (ProcessDefinition_PublishProcess.PublishId = @lastPublishedId)		
		  AND     (ProcessDefinition_ProcessHistory.PrettyPostTitle LIKE @PostTitle) 
		  AND (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)
	END
	ELSE 
     IF(@projectId IS NULL AND @TaskId IS NULL)
	BEGIN
		SELECT     ProcessDefinition_Process.ForeignType, ProcessDefinition_Process.ForeignId, ProcessDefinition_Process.DateCreated, 
							  ProcessDefinition_Process.ProcessDescription, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.IsPublished, 
							  ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.MajorVersion, ProcessDefinition_Process.MinorVersion, 
							  ProcessDefinition_Process.ProcessTypeId, ProcessDefinition_ProcessType.ProcessTypeName, DateFrozen, AltGroup,
							  NULL AS ProcessHistoryId
		FROM         ProcessDefinition_Process INNER JOIN
							  ProcessDefinition_ProcessType ON ProcessDefinition_Process.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
		WHERE     (ProcessDefinition_Process.PrettyPostTitle LIKE @PostTitle) AND (ProcessDefinition_Process.ForeignId = @RepositoryId)

	END
	ELSE IF(@TaskId IS NULL)
	BEGIN

		SELECT     ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, 
							  ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, 
							  ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, 
							  ProcessDefinition_ProjectProcessType.ProcessTypeId, ProcessDefinition_ProjectProcessType.ProcessTypeName, DateFrozen, AltGroup,
							  NULL AS ProcessHistoryId
		FROM         ProcessDefinition_ProjectProcessType INNER JOIN
							  ProcessDefinition_ProjectProcessVersion INNER JOIN
							  ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId ON 
							  ProcessDefinition_ProjectProcessType.ProcessTypeId = ProcessDefinition_ProcessHistory.ProcessTypeId
		WHERE     (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectId) AND (ProcessDefinition_ProcessHistory.PrettyPostTitle LIKE @PostTitle) AND 
							  (ProcessDefinition_ProjectProcessType.ProjectPlanId = @projectId)

	END
	ELSE
	BEGIN
		
	    SELECT     ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, 
							 ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, 
							 ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, 
							 ProcessDefinition_ProjectProcessType.ProcessTypeId, ProcessDefinition_ProjectProcessType.ProcessTypeName, 
							 ProcessDefinition_ProcessHistory.DateFrozen, AltGroup,ProcessDefinition_ProcessHistory.ProcessHistoryId
	    FROM         ProcessDefinition_ProjectProcessType INNER JOIN
							 ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessType.ProcessTypeId = ProcessDefinition_ProcessHistory.ProcessTypeId INNER JOIN
							 ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProjectPlanTask.ProcessHistoryId
	    WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @TaskId)

	END
	
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanRoleAssignment]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanRoleAssignment]
(
[RoleAssignmentId] [int] NOT NULL IDENTITY(1, 1),
[TaskId] [int] NOT NULL,
[RoleProcessId] [int] NOT NULL,
[AssignedToId] [int] NOT NULL,
[AssignedById] [int] NOT NULL,
[AssignmentNote] [nvarchar] (max) NOT NULL,
[AssignmentDate] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlanRoleAssignment_AssignmentDate] DEFAULT (getutcdate()),
[GroupingGuid] [uniqueidentifier] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanRoleAssignment] on [dbo].[ProcessDefinition_ProjectPlanRoleAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanRoleAssignment] ON [dbo].[ProcessDefinition_ProjectPlanRoleAssignment] ([TaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanRoleAssignment_1] on [dbo].[ProcessDefinition_ProjectPlanRoleAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanRoleAssignment_1] ON [dbo].[ProcessDefinition_ProjectPlanRoleAssignment] ([RoleProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanRoleAssignment_2] on [dbo].[ProcessDefinition_ProjectPlanRoleAssignment]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanRoleAssignment_2] ON [dbo].[ProcessDefinition_ProjectPlanRoleAssignment] ([AssignedToId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlan]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlan]
(
[ProjectPlanId] [int] NOT NULL IDENTITY(1, 1),
[ProjectId] [int] NOT NULL,
[DateCreated] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectPlan_DateCreated] DEFAULT (getutcdate()),
[ProjectPlanName] [nvarchar] (256) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlan] on [dbo].[ProcessDefinition_ProjectPlan]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlan] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlan] PRIMARY KEY CLUSTERED  ([ProjectPlanId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlan_ProjectId] on [dbo].[ProcessDefinition_ProjectPlan]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlan_ProjectId] ON [dbo].[ProcessDefinition_ProjectPlan] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProjectAssignment]'
GO

CREATE PROCEDURE [dbo].[Report_ProjectAssignment] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL


SELECT  ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, ProcessDefinition_ProcessHistory.ProcessTitle AS tf_Role,  
	Assignment.AssignedDate  AS dtl_Assigned, 
	AssignedTo.DisplayName AS tf_AssignedTo, 
	AssignedTo.MemberEmailAddress AS tf_AssignedToEmail, 
	AssignedBy.DisplayName AS tf_AssignedBy, 
	AssignedBy.MemberEmailAddress AS tf_AssignedByEmail, 
	'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link                      
FROM         Account_User AS AssignedBy INNER JOIN
                      ProcessDefinition_ProjectPlanTask INNER JOIN

(SELECT     ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedToId, ProcessDefinition_ProjectPlanTaskAssignment_1.TaskId, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignmentDate, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedDate) AS AssignedDate, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignedById, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedById) AS AssignedById, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignmentNote, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignmentNote) AS AssignmentNote, 
	ProcessDefinition_ProjectPlanRoleAssignment_1.RoleProcessId
    FROM          ProcessDefinition_ProjectPlanTaskAssignment AS ProcessDefinition_ProjectPlanTaskAssignment_1 LEFT OUTER JOIN
                           ProcessDefinition_ProjectPlanRoleAssignment AS ProcessDefinition_ProjectPlanRoleAssignment_1 ON 
                           ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedToId = ProcessDefinition_ProjectPlanRoleAssignment_1.AssignedToId AND 
                           ProcessDefinition_ProjectPlanTaskAssignment_1.TaskId = ProcessDefinition_ProjectPlanRoleAssignment_1.TaskId) AS Assignment ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = Assignment.TaskId ON AssignedBy.UserId = Assignment.AssignedById INNER JOIN
                      Account_User AS AssignedTo ON Assignment.AssignedToId = AssignedTo.UserId INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
                      ProcessDefinition_ProjectProcessVersion INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId ON 
                      Assignment.RoleProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId AND 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectProcessVersion.ProjectPlanId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))
ORDER BY dd_ProjectName, tf_Task




END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UserType]'
GO
CREATE TABLE [dbo].[Account_UserType]
(
[PrimaryUserTypeId] [int] NOT NULL,
[PrimaryUserTypeName] [nvarchar] (100) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Account_UserType] on [dbo].[Account_UserType]'
GO
ALTER TABLE [dbo].[Account_UserType] ADD CONSTRAINT [PK_Account_UserType] PRIMARY KEY CLUSTERED  ([PrimaryUserTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUserTypes]'
GO
CREATE PROCEDURE [dbo].[Account_GetUserTypes] 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     PrimaryUserTypeId, PrimaryUserTypeName
	FROM         Account_UserType
	ORDER BY PrimaryUserTypeName

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllUnremovedTasks]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_GetAllUnremovedTasks] 
(	
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(

WITH UnRemovedTasks (ParentTaskId, ProjectPlanTaskId)
AS
(

	SELECT     ParentTaskId, ProjectPlanTaskId
	FROM         ProcessDefinition_ProjectPlanTask
	WHERE     (ParentTaskId IS NULL) AND (TaskIsRemoved = 0)

    UNION ALL

	SELECT     ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
	FROM         ProcessDefinition_ProjectPlanTask
		INNER JOIN UnRemovedTasks ON UnRemovedTasks.ProjectPlanTaskId=ProcessDefinition_ProjectPlanTask.ParentTaskId
	WHERE      (TaskIsRemoved = 0)
)

SELECT ParentTaskId, ProjectPlanTaskId FROM UnRemovedTasks


)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Step]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Step]
(
[ProcessStepId] [int] NOT NULL IDENTITY(1, 1),
[ParentProcessId] [int] NOT NULL,
[StepName] [nvarchar] (256) NOT NULL,
[StepDescription] [nvarchar] (max) NOT NULL,
[ChildProcessId] [int] NULL,
[StepPosition] [int] NOT NULL,
[StepType] [int] NOT NULL,
[IterationDescription] [nvarchar] (1024) NOT NULL,
[OptionalDescription] [nvarchar] (1024) NOT NULL,
[StepUId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ProcessDefinition_Step_UniqueId] DEFAULT (newid()),
[bpmnJson] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Step] on [dbo].[ProcessDefinition_Step]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Step] ADD CONSTRAINT [PK_ProcessDefinition_Step] PRIMARY KEY CLUSTERED  ([ProcessStepId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Step_ParentProcessId] on [dbo].[ProcessDefinition_Step]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Step_ParentProcessId] ON [dbo].[ProcessDefinition_Step] ([ParentProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Step_ChildProcessId] on [dbo].[ProcessDefinition_Step]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Step_ChildProcessId] ON [dbo].[ProcessDefinition_Step] ([ChildProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesLinkUsage]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesLinkUsage] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessId, 
			SectionName, 
			LinkText, 
			ProcessTitle, 
			PrettyPostTitle, 
			DescriptionSnippet,
			ProcessTypeId,
			LinkType,
			SectionDirection
	FROM         (
	SELECT     ProcessDefinition_ProcessLink.ProcessId, 
				ProcessDefinition_ProcessLink.SectionName, 
				ProcessDefinition_ProcessLink.LinkText, 
				ProcessDefinition_Process.ProcessTitle, 
				ProcessDefinition_Process.PrettyPostTitle, 
				ProcessDefinition_Process.DescriptionSnippet,
				ProcessDefinition_Process.ProcessTypeId,
				LinkType, SectionDirection
	FROM         ProcessDefinition_ProcessLink INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProcessLink.ProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_ProcessLink.LinksToProcessId = @processId) AND (ProcessDefinition_Process.IsDeleted=0)
	GROUP BY ProcessDefinition_ProcessLink.ProcessId, ProcessDefinition_ProcessLink.SectionName, ProcessDefinition_ProcessLink.LinkText, 
						  ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle, 
			ProcessDefinition_Process.DescriptionSnippet, ProcessTypeId, LinkType, SectionDirection
	UNION
SELECT     ProcessDefinition_Process.ProcessId, 'Steps' AS SectionName, ProcessDefinition_Step.StepName AS LinkText, ProcessDefinition_Process.ProcessTitle, 
                      ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.DescriptionSnippet,
			ProcessDefinition_Process.ProcessTypeId, CASE WHEN ((ProcessDefinition_Step.StepType & 4) > 0) THEN 4 ELSE 0 END AS LinkType, '' AS SectionDirection
FROM         ProcessDefinition_Step INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_Step.ParentProcessId = ProcessDefinition_Process.ProcessId
WHERE     (ProcessDefinition_Step.ChildProcessId = @processId) AND (ProcessDefinition_Process.IsDeleted=0)
GROUP BY ProcessDefinition_Process.ProcessId, ProcessDefinition_Step.StepName, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle, 
                      ProcessDefinition_Process.DescriptionSnippet, ProcessTypeId, ProcessDefinition_Step.StepType
	) AS Links

	ORDER BY Links.SectionName, Links.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProcessesChangedAfterFreezing]'
GO
CREATE PROCEDURE [dbo].[Report_ProcessesChangedAfterFreezing] 
		@repositoryName varchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)


    	SELECT     ProcessDefinition_ProcessHistory.ProcessTitle, '~/' + ProcessDefinition_ProcessHistory.PrettyPostTitle AS link_Process
FROM         ProcessDefinition_ProcessHistory INNER JOIN
                      ProcessDefinition_ProcessHistory AS PH ON ProcessDefinition_ProcessHistory.ProcessId = PH.ProcessId AND 
                      ProcessDefinition_ProcessHistory.ProcessHistoryId < PH.ProcessHistoryId
WHERE     (PH.IsFrozenVersion = 1) AND (PH.IsLatestVersion = 0) AND (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)
ORDER BY ProcessDefinition_ProcessHistory.ProcessTitle
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcess]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcess]
(
     @processId int,
      @ProcessDescription nvarchar(max),
      @ProcessTitle nvarchar(256),
	@PrettyPostTitle nvarchar(256),
      @IsPublished bit,
	@DescriptionSnippet nvarchar(1024),
	@ProcessTypeId int,
	@IsFreeze bit,
	@AltGroup nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @historyId int

		DECLARE @MajorVersion int, @MinorVersion int
	SELECT @MajorVersion = MajorVersion, @MinorVersion = MinorVersion 
		FROM ProcessDefinition_Process 
		WHERE ProcessId = @processId
	
						IF((@IsFreeze != 0 AND @MajorVersion != @MinorVersion) OR (@IsFreeze = 0 AND @MajorVersion = @MinorVersion))
	BEGIN
		SET @MajorVersion = @MajorVersion + 1
	END	

		UPDATE    ProcessDefinition_Process
	SET              ProcessDescription = @ProcessDescription, ProcessTitle = @ProcessTitle, IsPublished = @IsPublished, DateUpdated = GETUTCDATE(), 
						  DescriptionSnippet = @DescriptionSnippet, MajorVersion=@MajorVersion, MinorVersion=MinorVersion+1,
				DateFrozen = CASE @IsFreeze WHEN 0 THEN NULL ELSE GetUtcDate() END, AltGroup = @AltGroup
	WHERE     (ProcessId = @processId)

	IF @ProcessTypeId IS NOT NULL
	BEGIN
		UPDATE ProcessDefinition_Process
		SET ProcessTypeId=@ProcessTypeId
		WHERE     (ProcessId = @processId)
	END



END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTaskUpgrade]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTaskUpgrade]
(
[TaskUpgradeId] [int] NOT NULL IDENTITY(1, 1),
[TaskId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[DateUpgraded] [datetime] NOT NULL,
[OldProcessHistoryId] [int] NOT NULL,
[NewProcessHsitoryId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlanTaskUpgrade] on [dbo].[ProcessDefinition_ProjectPlanTaskUpgrade]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTaskUpgrade] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlanTaskUpgrade] PRIMARY KEY CLUSTERED  ([TaskUpgradeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTaskEvent]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTaskEvent]
(
[TaskUpdateEventId] [int] NOT NULL IDENTITY(1, 1),
[TaskId] [int] NOT NULL,
[EventType] [int] NOT NULL,
[EstimatedStartDate] [datetime] NULL,
[EstimatedEndDate] [datetime] NULL,
[ProgressPc] [int] NULL,
[UserId] [int] NOT NULL,
[EventDate] [datetime] NOT NULL,
[CurrentStatus] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlanTaskEvent] on [dbo].[ProcessDefinition_ProjectPlanTaskEvent]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTaskEvent] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlanTaskEvent] PRIMARY KEY CLUSTERED  ([TaskUpdateEventId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectPlanTaskEvent] on [dbo].[ProcessDefinition_ProjectPlanTaskEvent]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectPlanTaskEvent] ON [dbo].[ProcessDefinition_ProjectPlanTaskEvent] ([TaskId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProcessLinkHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProcessLinkHistory]
(
[ProcessLinkHistoryId] [int] NOT NULL IDENTITY(1, 1),
[ProcessId] [int] NOT NULL,
[SectionName] [nvarchar] (255) NULL,
[LinkUri] [nvarchar] (1024) NULL,
[LinksToProcessId] [int] NULL,
[FullLinkUri] [nvarchar] (1024) NOT NULL,
[LinkText] [nvarchar] (1024) NULL,
[MajorVersion] [int] NOT NULL,
[MinorVersion] [int] NOT NULL,
[ProcessHistoryId] [int] NOT NULL,
[LinkType] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProcessLinkHistory_LinkType] DEFAULT ((0)),
[LinkUid] [nvarchar] (50) NULL,
[SectionDirection] [nvarchar] (10) NULL,
[SectionMultiplicity] [nvarchar] (10) NULL,
[SectionType] [nvarchar] (128) NULL,
[SectionLinkTypeId] [int] NULL,
[ExcludedLinksToProcessId] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProcessLinkHistory] on [dbo].[ProcessDefinition_ProcessLinkHistory]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProcessLinkHistory] ADD CONSTRAINT [PK_ProcessDefinition_ProcessLinkHistory] PRIMARY KEY CLUSTERED  ([ProcessLinkHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_Data]'
GO
CREATE TABLE [dbo].[Metadata_Data]
(
[MetadataDataId] [int] NOT NULL IDENTITY(1, 1),
[MetadataId] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[StringValue] [nvarchar] (max) NULL,
[IntValue] [int] NULL,
[BoolValue] [bit] NULL,
[DoubleValue] [float] NULL,
[DateValue] [datetime] NULL,
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_Metadata_Data_IsDeleted] DEFAULT ((0)),
[DateChanged] [datetime] NULL,
[ChangedByUserId] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Metadata_Data] on [dbo].[Metadata_Data]'
GO
ALTER TABLE [dbo].[Metadata_Data] ADD CONSTRAINT [PK_Metadata_Data] PRIMARY KEY CLUSTERED  ([MetadataDataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_Data_MetadataId] on [dbo].[Metadata_Data]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_Data_MetadataId] ON [dbo].[Metadata_Data] ([MetadataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_Data_ForeignId] on [dbo].[Metadata_Data]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_Data_ForeignId] ON [dbo].[Metadata_Data] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_Data_ForeignType] on [dbo].[Metadata_Data]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_Data_ForeignType] ON [dbo].[Metadata_Data] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProjectActivity]'
GO

CREATE PROCEDURE [dbo].[Report_ProjectActivity] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

SELECT  ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
		Assignment.AssignedDate AS dtl_EventDate, 'Task assignment' AS dd_EventType, 
		AssignedTo.DisplayName + ' (' + COALESCE(ProcessDefinition_ProcessHistory.ProcessTitle, 'No role') + ')' AS tf_EventInformation, 	
	'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link                      
FROM         Account_User AS AssignedBy INNER JOIN
                      ProcessDefinition_ProjectPlanTask INNER JOIN

(SELECT     ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedToId, ProcessDefinition_ProjectPlanTaskAssignment_1.TaskId, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignmentDate, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedDate) AS AssignedDate, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignedById, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedById) AS AssignedById, 
	COALESCE (ProcessDefinition_ProjectPlanRoleAssignment_1.AssignmentNote, ProcessDefinition_ProjectPlanTaskAssignment_1.AssignmentNote) AS AssignmentNote, 
	ProcessDefinition_ProjectPlanRoleAssignment_1.RoleProcessId
    FROM          ProcessDefinition_ProjectPlanTaskAssignment AS ProcessDefinition_ProjectPlanTaskAssignment_1 LEFT OUTER JOIN
                           ProcessDefinition_ProjectPlanRoleAssignment AS ProcessDefinition_ProjectPlanRoleAssignment_1 ON 
                           ProcessDefinition_ProjectPlanTaskAssignment_1.AssignedToId = ProcessDefinition_ProjectPlanRoleAssignment_1.AssignedToId AND 
                           ProcessDefinition_ProjectPlanTaskAssignment_1.TaskId = ProcessDefinition_ProjectPlanRoleAssignment_1.TaskId) AS Assignment ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = Assignment.TaskId ON AssignedBy.UserId = Assignment.AssignedById INNER JOIN
                      Account_User AS AssignedTo ON Assignment.AssignedToId = AssignedTo.UserId INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
                      ProcessDefinition_ProjectProcessVersion INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId ON 
                      Assignment.RoleProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId AND 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectProcessVersion.ProjectPlanId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION

SELECT  ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
		ProcessDefinition_ProjectPlanTask.DateUpdated AS dtl_EventDate, 'Task updated' AS dd_EventType, DisplayName AS tf_EventInformation, 	
	'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link                      
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanTask.EditorUserId = Account_User.UserId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION

SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
                      ProcessDefinition_ProjectPlanTaskUpgrade.DateUpgraded AS dtl_EventDate, 'Task upgraded' AS dd_EventType, Account_User.DisplayName AS tf_EventInformation, 
                      '~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) 
                      + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link 
FROM         ProcessDefinition_ProjectPlanTaskUpgrade INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanTaskUpgrade.UserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId ON 
                      ProcessDefinition_ProjectPlanTaskUpgrade.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))


UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
			ProcessDefinition_ProjectPlanTask.ActualStartDate AS dtl_EventDate, 'Task started' AS dd_EventType, 
                      Account_User.DisplayName AS tf_EventInformation, 
'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanTask.StartedUserId = Account_User.UserId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
			ProcessDefinition_ProjectPlanTask.ActualEndDate AS dtl_EventDate, 'Task finished' AS dd_EventType, 
                      Account_User.DisplayName AS tf_EventInformation, 
'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanTask.StartedUserId = Account_User.UserId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, 
			ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
			ProcessDefinition_ProjectPlanTaskEvent.EventDate AS dtl_EventDate, 
			CASE EventType 
				WHEN 1 THEN 'Estimates updated'
				WHEN 2 THEN 'Progress updated'
				WHEN 3 THEN 'Status updated' 
				END AS dd_EventType, 
	Account_User.DisplayName AS tf_EventInformation, 
                      '~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) 
                      + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link
FROM   ProcessDefinition_ProjectPlanTaskEvent INNER JOIN
	Account_User ON ProcessDefinition_ProjectPlanTaskEvent.UserId = Account_User.UserId INNER JOIN
    ProcessDefinition_ProjectPlanTask INNER JOIN
    ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId ON 
    ProcessDefinition_ProjectPlanTaskEvent.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION

SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
	Metadata_Data.DateChanged AS dtl_EventDate, 'Data updated' AS dd_EventType, 
                      Account_User.DisplayName AS tf_EventInformation, 
'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId INNER JOIN
                      Metadata_Data ON ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = Metadata_Data.ForeignId INNER JOIN
                      Account_User ON Metadata_Data.ChangedByUserId = Account_User.UserId
WHERE  ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))
 AND (Metadata_Data.ForeignType = 15)

UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, ProcessDefinition_ProjectPlanTask.TaskName AS tf_Task, 
                      Metadata_Data.DateChanged AS dtl_EventDate, 'Linked data updated' AS dd_EventType, 
		Account_User.DisplayName + ' (' + ProcessDefinition_ProcessLinkHistory.SectionName +', ' + ProcessDefinition_ProcessHistory.ProcessTitle + ')' AS tf_EventInformation, 
                      '~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) 
                      + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link                       
FROM         ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                      ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId ON 
                      ProcessDefinition_ProjectPlanTaskLink.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      Account_User INNER JOIN
                      Metadata_Data ON Account_User.UserId = Metadata_Data.ChangedByUserId ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId = Metadata_Data.ForeignId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))
 AND (Metadata_Data.ForeignType = 14)
ORDER BY dtl_EventDate DESC, dd_ProjectName, tf_Task

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_MissingSignedOffExceptions]'
GO

CREATE PROCEDURE [dbo].[Review_MissingSignedOffExceptions] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

	SELECT    ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, PPT.TaskName,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(PPT.ProjectPlanId as nvarchar(12))+'|'+CAST(PPT.ProjectPlanTaskId as nvarchar(12)) AS flink_Link
	FROM         ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
						  dbo.ProcessDefinition_GetAllUnremovedTasks() AS UnremovedTasks ON PPT.ProjectPlanTaskId = UnremovedTasks.ProjectPlanTaskId INNER JOIN
						  ProcessDefinition_ProjectPlan ON PPT.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE     (PPT.CurrentStatus = 4) AND (PPT.StatusNotes = '') AND (ProcessDefinition_ProjectPlan.ProjectId = @projectId)
AND
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId))

	ORDER BY ProcessDefinition_ProjectPlan.ProjectPlanName, PPT.TaskName

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_MissingStepDeletionReason]'
GO


CREATE PROCEDURE [dbo].[Review_MissingStepDeletionReason] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

	SELECT PP.ProjectPlanName AS dd_ProjectName, PPT.TaskName,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(PPT.ProjectPlanId as nvarchar(12))+'|'+CAST(PPT.ParentTaskId as nvarchar(12)) AS flink_Link
	FROM ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
		 ProcessDefinition_ProjectPlan AS PP ON PP.ProjectPlanId = PPT.ProjectPlanId
	WHERE PPT.TaskIsRemoved = 1 AND PPT.RemovalReason = '' AND PP.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId))

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_StepsWithoutTextDescription]'
GO
CREATE PROCEDURE [dbo].[Review_StepsWithoutTextDescription]
		@repositoryName varchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    	SELECT     ProcessDefinition_Project.ProjectName AS dd_ProjectName, ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectPlanName, ProcessDefinition_ProjectPlanTask.TaskName
	FROM         dbo.ProcessDefinition_GetAllUnremovedTasks() AS ProcessDefinition_GetAllUnremovedTasks_1 INNER JOIN
						  ProcessDefinition_ProjectPlanTask ON 
						  ProcessDefinition_GetAllUnremovedTasks_1.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_ProjectPlanTask.TaskNotes = '') AND ProcessDefinition_Project.RepositoryId = @RepositoryId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ChangeRepositoryAccess]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ChangeRepositoryAccess] 
		@repositoryName nvarchar(256),
    @userId int,
    @MemberRole int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	UPDATE ProcessDefinition_Member SET MemberRole = @MemberRole, UserAssigned = 1
	WHERE     (RepositoryId = @RepositoryId) AND (UserId = @userId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_ProcessesNoTags]'
GO
CREATE PROCEDURE [dbo].[Review_ProcessesNoTags] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    	SELECT DISTINCT PH.ProcessTitle, '~/' + PH.PrettyPostTitle AS link_Process
	FROM         ProcessDefinition_ProcessHistory AS PH LEFT OUTER JOIN
                      Notes_AssignedTag ON PH.ProcessId = Notes_AssignedTag.ForeignId
	WHERE     (Notes_AssignedTag.TagId IS NULL) AND (PH.ForeignId = @RepositoryId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_TasksDueToStart]'
GO

CREATE PROCEDURE [dbo].[Report_TasksDueToStart] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

	SELECT PP.ProjectPlanName AS dd_ProjectName, PPT.TaskName AS dd_TaskName, PPT.EstimatedStartDate AS dtl_StartDate, PPT.EstimatedEndDate AS dtl_EndDate, 
		CASE PPT.CurrentStatus WHEN 1 THEN 'Not started' WHEN 2 THEN 'Started' END AS CurrentStatus ,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(PPT.ProjectPlanId as nvarchar(12))+'|'+CAST(PPT.ProjectPlanTaskId as nvarchar(12)) AS flink_Link
	FROM ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
		 ProcessDefinition_ProjectPlan AS PP ON PP.ProjectPlanId = PPT.ProjectPlanId
	WHERE 
		(PPT.CurrentStatus = 1 AND PPT.EstimatedStartDate < DateDiff(day,-2,GetUtcDate()) AND PPT.EstimatedStartDate > GetUtcDate())
		AND (PPT.TaskIsRemoved=0)
		AND PP.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId))


END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CheckProcessRepository]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_CheckProcessRepository] 
(
	@processId int,
	@reposName nvarchar(256)
)
RETURNS int
WITH ENCRYPTION AS
BEGIN
		DECLARE @Result int

	SELECT     @Result=ProcessDefinition_Process.ProcessId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @reposName) AND (ProcessDefinition_Process.ProcessId = @processId)

	IF(@Result IS NULL)
		SET @Result = 0

		RETURN @Result

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessRelationshipGraph]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessRelationshipGraph]
(
	@repositoryName nvarchar(256),
      @processId int,
      @RelationshipGraph nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	IF(dbo.ProcessDefinition_CheckProcessRepository(@processId, @repositoryName) = @processId)
	BEGIN
						UPDATE ProcessDefinition_Process
		SET RelationshipGraph = @RelationshipGraph
		WHERE  ProcessId=@processId

				UPDATE ProcessDefinition_ProcessHistory
		SET RelationshipGraph = @RelationshipGraph
		WHERE  ProcessId=@processId AND IsLatestVersion = 1
		
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Utils_StringLookup]'
GO
CREATE TABLE [dbo].[Utils_StringLookup]
(
[StringLookupId] [int] NOT NULL IDENTITY(1, 1),
[LookupString] [nvarchar] (4000) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Utils_StringLookup] on [dbo].[Utils_StringLookup]'
GO
ALTER TABLE [dbo].[Utils_StringLookup] ADD CONSTRAINT [PK_Utils_StringLookup] PRIMARY KEY CLUSTERED  ([StringLookupId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Utils_GetStringId]'
GO
CREATE PROCEDURE [dbo].[Utils_GetStringId] 
	@lookupString nvarchar(4000)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @ret int

	SELECT     @ret=StringLookupId
	FROM         Utils_StringLookup
	WHERE     (LookupString = @lookupString)

	IF(@ret IS NULL)
	BEGIN

		INSERT INTO Utils_StringLookup
						  (LookupString)
				VALUES     (@lookupString)

		SET @ret=Scope_Identity()
	END

	SELECT @ret

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_OverDueTasks]'
GO

CREATE PROCEDURE [dbo].[Report_OverDueTasks] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL


	SELECT PP.ProjectPlanName AS dd_ProjectName, PPT.TaskName AS dd_TaskName, PPT.EstimatedStartDate AS dtl_StartDate, PPT.EstimatedEndDate AS dtl_EndDate, 
		CASE PPT.CurrentStatus WHEN 1 THEN 'Not started' WHEN 2 THEN 'Started' END AS CurrentStatus,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(PPT.ProjectPlanId as nvarchar(12))+'|'+CAST(PPT.ProjectPlanTaskId as nvarchar(12)) AS flink_Link
	FROM ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
		 ProcessDefinition_ProjectPlan AS PP ON PP.ProjectPlanId = PPT.ProjectPlanId
	WHERE 
		((PPT.CurrentStatus = 1 AND PPT.EstimatedStartDate < GetUtcDate())
		OR 
		(PPT.CurrentStatus = 2 AND PPT.EstimatedEndDate < GetUtcDate()))
		AND (PPT.TaskIsRemoved=0)
		AND PP.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId))
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMetricSummary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMetricSummary] 
	@repositoryName nvarchar(256),
	@projectId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @dtNow DateTime
	SET @dtNow=GetUtcDate()

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	

	SELECT     CASE WHEN DATEDIFF(month, ReposMetrics.DateChanged, @dtNow) >= 12 THEN 13 ELSE DATEDIFF(month, ReposMetrics.DateChanged, @dtNow) 
						  END AS MonthNum, COUNT(DISTINCT ReposMetrics.MetadataDataId) AS MonthlyCount
	FROM         (
SELECT     Metadata_Data.DateChanged, Metadata_Data.MetadataDataId
FROM         Metadata_Data INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (Metadata_Data.ForeignType = 15) AND (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)

UNION

SELECT     Metadata_Data.DateChanged, Metadata_Data.MetadataDataId
FROM         Metadata_Data INNER JOIN
                      ProcessDefinition_ProjectPlanTaskLink ON Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (Metadata_Data.ForeignType = 14) AND (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)

) AS ReposMetrics
	GROUP BY DATEDIFF(month, ReposMetrics.DateChanged, @dtNow)
	ORDER BY MonthNum DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessRelationshipGraph]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessRelationshipGraph]
(
    @processId int,
    @processHistoryId int,
	@useFrozen bit
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

		
	IF(@processHistoryId IS NULL)
	BEGIN
		SELECT RelationshipGraph FROM ProcessDefinition_ProcessHistory
		WHERE  (ProcessDefinition_ProcessHistory.ProcessId = @processId)
			AND ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))
	END
	ELSE
	BEGIN
		SELECT RelationshipGraph FROM ProcessDefinition_ProcessHistory
		WHERE  (ProcessDefinition_ProcessHistory.ProcessHistoryId = @processHistoryId) AND (ProcessId = @processId) 	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UserRoleMapping]'
GO
CREATE TABLE [dbo].[Account_UserRoleMapping]
(
[UserTypeRoleId] [int] NOT NULL IDENTITY(1, 1),
[DotNetRoleId] [int] NOT NULL,
[PrimaryUserTypeId] [int] NOT NULL,
[IsMandatory] [bit] NOT NULL,
[DefaultValue] [bit] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Account_UserRoleMapping] on [dbo].[Account_UserRoleMapping]'
GO
ALTER TABLE [dbo].[Account_UserRoleMapping] ADD CONSTRAINT [PK_Account_UserRoleMapping] PRIMARY KEY CLUSTERED  ([UserTypeRoleId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Account_UserRoleMapping_DotNetRoleId] on [dbo].[Account_UserRoleMapping]'
GO
CREATE NONCLUSTERED INDEX [IX_Account_UserRoleMapping_DotNetRoleId] ON [dbo].[Account_UserRoleMapping] ([DotNetRoleId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Account_UserRoleMapping_PrimaryUserTypeId] on [dbo].[Account_UserRoleMapping]'
GO
CREATE NONCLUSTERED INDEX [IX_Account_UserRoleMapping_PrimaryUserTypeId] ON [dbo].[Account_UserRoleMapping] ([PrimaryUserTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_DotNetRole]'
GO
CREATE TABLE [dbo].[Account_DotNetRole]
(
[DotNetRoleId] [int] NOT NULL,
[RoleName] [nvarchar] (100) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Account_DotNetRole] on [dbo].[Account_DotNetRole]'
GO
ALTER TABLE [dbo].[Account_DotNetRole] ADD CONSTRAINT [PK_Account_DotNetRole] PRIMARY KEY CLUSTERED  ([DotNetRoleId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetOptionalRoles]'
GO
CREATE PROCEDURE [dbo].[Account_GetOptionalRoles] 
		@userType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Account_DotNetRole.DotNetRoleId, Account_UserRoleMapping.DefaultValue, Account_DotNetRole.RoleName
	FROM         Account_UserRoleMapping INNER JOIN
						  Account_DotNetRole ON Account_UserRoleMapping.DotNetRoleId = Account_DotNetRole.DotNetRoleId
	WHERE     (Account_UserRoleMapping.PrimaryUserTypeId = @userType) AND (Account_UserRoleMapping.IsMandatory = 0)
	ORDER BY Account_DotNetRole.RoleName

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Access]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Access]
(
[ProcessAccessId] [int] NOT NULL IDENTITY(1, 1),
[UserId] [int] NOT NULL,
[DateAccessed] [datetime] NOT NULL,
[ProcessId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Access] on [dbo].[ProcessDefinition_Access]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Access] ADD CONSTRAINT [PK_ProcessDefinition_Access] PRIMARY KEY CLUSTERED  ([ProcessAccessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Access_UserId] on [dbo].[ProcessDefinition_Access]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Access_UserId] ON [dbo].[ProcessDefinition_Access] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Access_ProcessId] on [dbo].[ProcessDefinition_Access]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Access_ProcessId] ON [dbo].[ProcessDefinition_Access] ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUserAccessSummary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetUserAccessSummary] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @dtNow DateTime
	SET @dtNow=GetUtcDate()
	SELECT     CASE WHEN DATEDIFF(month, ProcessDefinition_Access.DateAccessed, @dtNow) >= 12 THEN 13 ELSE DATEDIFF(month, ProcessDefinition_Access.DateAccessed, 
						  @dtNow) END AS MonthNum, COUNT(DISTINCT ProcessDefinition_Access.ProcessId) AS MonthlyCount
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId INNER JOIN
						  ProcessDefinition_Access ON ProcessDefinition_Process.ProcessId = ProcessDefinition_Access.ProcessId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)
	GROUP BY DATEDIFF(month, ProcessDefinition_Access.DateAccessed, @dtNow)
	ORDER BY MonthNum DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_StepHistory]
(
[StepHistoryId] [int] NOT NULL IDENTITY(1, 1),
[ProcessStepId] [int] NOT NULL,
[ParentProcessId] [int] NOT NULL,
[StepName] [nvarchar] (256) NOT NULL,
[StepDescription] [nvarchar] (max) NOT NULL,
[ChildProcessId] [int] NULL,
[StepPosition] [int] NOT NULL,
[StepType] [int] NOT NULL,
[IterationDescription] [nvarchar] (1024) NOT NULL,
[OptionalDescription] [nvarchar] (1024) NOT NULL,
[MajorVersion] [int] NOT NULL,
[MinorVersion] [int] NOT NULL,
[ProcessHistoryId] [int] NOT NULL,
[bpmnJson] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_StepHistory] on [dbo].[ProcessDefinition_StepHistory]'
GO
ALTER TABLE [dbo].[ProcessDefinition_StepHistory] ADD CONSTRAINT [PK_ProcessDefinition_StepHistory] PRIMARY KEY CLUSTERED  ([StepHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_StepHistory_ProcessStepId] on [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_StepHistory_ProcessStepId] ON [dbo].[ProcessDefinition_StepHistory] ([ProcessStepId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_StepHistory_ParentProcessId] on [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_StepHistory_ParentProcessId] ON [dbo].[ProcessDefinition_StepHistory] ([ParentProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_StepHistory_ChildProcessId] on [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_StepHistory_ChildProcessId] ON [dbo].[ProcessDefinition_StepHistory] ([ChildProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_StepHistory_MajorVersion] on [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_StepHistory_MajorVersion] ON [dbo].[ProcessDefinition_StepHistory] ([MajorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_StepHistory_MinorVersion] on [dbo].[ProcessDefinition_StepHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_StepHistory_MinorVersion] ON [dbo].[ProcessDefinition_StepHistory] ([MinorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_HasPostAccess]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_HasPostAccess] 
(
	@Post nvarchar(256),
	@repositoryName nvarchar(256),
	@userId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN

		DECLARE @processId int
	DECLARE @RepositoryId int
	SELECT  @processId=   ProcessDefinition_Process.ProcessId, @RepositoryId=RepositoryId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId 
	WHERE     (ProcessDefinition_Process.PrettyPostTitle LIKE @Post) AND (ProcessDefinition_Repository.RepositoryName = @repositoryName)

	
	DECLARE @HasPostAccess bit

		IF(@processId IN ( 
		SELECT     ProcessDefinition_ProjectPlanTask.TaskProcessId AS ProcessId
		FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
							  ProcessDefinition_ProjectPlanTaskAssignment ON 
							  ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
		WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId)

		UNION

		SELECT     ProcessDefinition_ProjectPlanTaskLink.LinksToProcessId AS ProcessId
		FROM         ProcessDefinition_ProjectPlanTaskAssignment INNER JOIN
							  ProcessDefinition_ProjectPlanTaskLink ON ProcessDefinition_ProjectPlanTaskAssignment.TaskId = ProcessDefinition_ProjectPlanTaskLink.TaskId
		WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId)
		)
	)
	BEGIN

		SET @HasPostAccess=1

	END
	ELSE
	BEGIN

		DECLARE @MemberRole int
		SELECT     @MemberRole= MemberRole
		FROM         ProcessDefinition_Member
		WHERE     (UserId = @userId) AND (RepositoryId = @RepositoryId)

		IF(@MemberRole>=3)
		BEGIN
						SET @HasPostAccess=1
		END


	END


	RETURN  @HasPostAccess 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO


GO
PRINT N'Creating [dbo].[Metadata_MetadataField]'
GO
CREATE TABLE [dbo].[Metadata_MetadataField]
(
[MetadataId] [int] NOT NULL IDENTITY(1, 1),
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[MetadataType] [nvarchar] (100) NOT NULL,
[IsMandatory] [bit] NOT NULL,
[Position] [int] NOT NULL,
[ScreenLabel] [nvarchar] (100) NULL,
[DefaultValue] [nvarchar] (100) NULL,
[AllowableValues] [nvarchar] (4000) NULL,
[CssClass] [nvarchar] (50) NULL,
[FormatInfo] [nvarchar] (50) NULL,
[ControlData] [nvarchar] (2000) NULL,
[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_Metadata_MetadataField_IsDeleted] DEFAULT ((0)),
[UniqueId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Metadata_MetadataField_UniqueId] DEFAULT (newid())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Metadata_MetadataField] on [dbo].[Metadata_MetadataField]'
GO
ALTER TABLE [dbo].[Metadata_MetadataField] ADD CONSTRAINT [PK_Metadata_MetadataField] PRIMARY KEY CLUSTERED  ([MetadataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_MetadataField_ForeignId] on [dbo].[Metadata_MetadataField]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_MetadataField_ForeignId] ON [dbo].[Metadata_MetadataField] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_MetadataField_ForeignType] on [dbo].[Metadata_MetadataField]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_MetadataField_ForeignType] ON [dbo].[Metadata_MetadataField] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMetricDefinitionSummary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMetricDefinitionSummary] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @reposMetrics int
	SELECT     @reposMetrics=COUNT(MetadataId)
	FROM         Metadata_MetadataField
	WHERE     (ForeignId = @RepositoryId) AND (ForeignType = 8)



	DECLARE @processMetrics int
	SELECT     @processMetrics=COUNT(Metadata_MetadataField.MetadataId)
	FROM         Metadata_MetadataField INNER JOIN
						  ProcessDefinition_Process ON Metadata_MetadataField.ForeignId = ProcessDefinition_Process.ProcessId
	WHERE     (Metadata_MetadataField.ForeignType = 7) AND (ProcessDefinition_Process.ForeignId = @RepositoryId)

	DECLARE @processCount int
	SELECT     @processCount=COUNT(ProcessId)
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId)

	DECLARE @userCount int
	SELECT     @userCount=COUNT(MemberId)
	FROM         ProcessDefinition_Member
	WHERE     (RepositoryId = @RepositoryId)


	SELECT @reposMetrics AS ReposMetrics,@processMetrics AS ProcessMetrics,
			@processCount AS ProcessCount,@userCount AS UserCount

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProcess]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProcess]
(
     @userId int,
      @repositoryName nvarchar(256),
      @ProcessDescription nvarchar(max),
      @ProcessTitle nvarchar(256),
		@PrettyPostTitle nvarchar(256),
      @IsPublished bit,
	@DescriptionSnippet nvarchar(1024),
	@ProcessTypeId int,
	@ProcessUId uniqueidentifier,
	@defnVersion int,
	@stepsSvg nvarchar(MAX)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
 
	IF(@RepositoryId IS NOT NULL)
	BEGIN

		IF(@ProcessUId IS NULL)
			SET @ProcessUId = NewId()

     INSERT INTO ProcessDefinition_Process
      (
            ForeignType, 
            ForeignId, 
            DateCreated, 
            ProcessDescription, 
            ProcessTitle, 
			PrettyPostTitle,
            IsPublished,
			DescriptionSnippet,
			UserId,
			ProcessTypeId,
			ProcessUId,
			StepDefinitionVersion,
			StepsSvg
      ) VALUES (
            7, 
            @RepositoryId, 
            GetUtcDate(), 
            @ProcessDescription, 
            @ProcessTitle, 
			@PrettyPostTitle,
            @IsPublished,
			@DescriptionSnippet,
			@userId,
			@ProcessTypeId,
			@ProcessUId,
			@defnVersion,
			@stepsSvg
      )

     DECLARE @newId int
     SET @newId = Scope_Identity()

			
	END


     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessHistoryDescription]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessHistoryDescription]
(
     @processHistoryId int,
      @ProcessDescription nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	UPDATE    ProcessDefinition_ProcessHistory
	SET              ProcessDescription = @ProcessDescription
	WHERE     (ProcessHistoryId = @processHistoryId)


END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcess]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcess]
(
     @processId int,
	@useFrozen bit
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
	SELECT     ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, 
						  ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, 
						  ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.ProcessTypeId, ProcessDefinition_ProcessType.ProcessTypeName,
				DateFrozen, ProcessHistoryId, AltGroup, ProcessDefinition_ProcessHistory.IsDeleted
	FROM         ProcessDefinition_ProcessHistory INNER JOIN
						  ProcessDefinition_ProcessType ON ProcessDefinition_ProcessHistory.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
	WHERE     (ProcessDefinition_ProcessHistory.ProcessId = @processId)
		AND ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProcessLinkData]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProcessLinkData]
(
[ProcessLinkDataId] [int] NOT NULL IDENTITY(1, 1),
[LinkUid] [nvarchar] (50) NOT NULL,
[ProcessId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProcessLinkData] on [dbo].[ProcessDefinition_ProcessLinkData]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProcessLinkData] ADD CONSTRAINT [PK_ProcessDefinition_ProcessLinkData] PRIMARY KEY CLUSTERED  ([ProcessLinkDataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkDataId]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkDataId]
	@uId nvarchar(50),
	@processId int,
	@LinkDataId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	SELECT @LinkDataId = ProcessLinkDataId FROM
	ProcessDefinition_ProcessLinkData
	WHERE ProcessId = @processId AND  LinkUid = @uId

	IF(@LinkDataId IS NULL)
	BEGIN
		INSERT INTO ProcessDefinition_ProcessLinkData(LinkUid, ProcessId)
		VALUES (@uId, @processId)
	
		SET @LinkDataId = Scope_Identity()
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ClearProcessHistoryLinks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ClearProcessHistoryLinks] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DELETE FROM ProcessDefinition_ProcessLinkHistory
	WHERE     (ProcessHistoryId = @processHistoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteProcess]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteProcess]
(
     @processId int,
	@userId int,
	@WithRename bit
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

		
	DECLARE @postTitle nvarchar(256) 
	DECLARE @prettyPostTitle nvarchar(256)
	DECLARE @isAlreadyDeleted bit

	SELECT @postTitle = ProcessTitle, @prettyPostTitle = PrettyPostTitle, @isAlreadyDeleted = IsDeleted
	FROM ProcessDefinition_Process
	WHERE (ProcessId = @processId)

	IF(@isAlreadyDeleted = 0)
	BEGIN
		IF(@WithRename = 1)
		BEGIN
						SET @postTitle = @postTitle + '-DEL-' + CAST(@processId AS nvarchar(20))
			SET @prettyPostTitle = @prettyPostTitle + '-DEL-' + CAST(@processId AS nvarchar(20))

			UPDATE ProcessDefinition_Process
			SET UserId =  @userId, IsDeleted=1, ProcessTitle = @postTitle, PrettyPostTitle = @prettyPostTitle
			WHERE (ProcessId = @processId)
		END
		ELSE
		BEGIN
						UPDATE ProcessDefinition_Process
			SET UserId =  @userId, IsDeleted=1
			WHERE (ProcessId = @processId)
		END
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AddProcessHistoryLink]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_AddProcessHistoryLink]
	@processHistoryId int,
	@processId int,
	@sectionName nvarchar(256),
	@linkUri nvarchar(1024),
	@fullLinkUri nvarchar(1024),
	@linksToProcessId int,
	@linkText nvarchar(1024),
	@linkType int,
	@linkUid nvarchar(50),
	@sectionDirection nvarchar(10),
	@sectionMultiplicity nvarchar(10),
	@sectionType nvarchar(128),
	@sectionLinkTypeId int,
	@MajorVersion int, 
	@MinorVersion int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

			DECLARE @excludedProcessId int
	SET @excludedProcessId = NULL
	IF((@linkType & 1) > 0)
	BEGIN
		SET @excludedProcessId = @linksToProcessId
		SET @linksToProcessId = NULL		
	END

	INSERT INTO ProcessDefinition_ProcessLinkHistory
		(ProcessId,ProcessHistoryId, SectionName, LinkUri, LinksToProcessId, FullLinkUri, 
		LinkText, LinkType, LinkUid, SectionDirection, SectionMultiplicity, SectionType, SectionLinkTypeId, ExcludedLinksToProcessId, MajorVersion, MinorVersion)
	VALUES     (@processId,@processHistoryId,@sectionName,@linkUri,@linksToProcessId,@fullLinkUri,
		@linkText, @linkType, @linkUid, @sectionDirection, @sectionMultiplicity, @sectionType, @sectionLinkTypeId, @excludedProcessId, @MajorVersion, @MinorVersion)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_Tag]'
GO
CREATE TABLE [dbo].[Notes_Tag]
(
[TagId] [int] NOT NULL IDENTITY(1, 1),
[TagName] [nvarchar] (100) NOT NULL,
[ForeignId] [int] NOT NULL CONSTRAINT [DF_Notes_Tag_ForeignId] DEFAULT ((0)),
[ForeignType] [int] NOT NULL CONSTRAINT [DF_Notes_Tag_ForeignType] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Notes_Tag] on [dbo].[Notes_Tag]'
GO
ALTER TABLE [dbo].[Notes_Tag] ADD CONSTRAINT [PK_Notes_Tag] PRIMARY KEY CLUSTERED  ([TagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_Tag_ForeignId] on [dbo].[Notes_Tag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_Tag_ForeignId] ON [dbo].[Notes_Tag] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_Tag_ForeignType] on [dbo].[Notes_Tag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_Tag_ForeignType] ON [dbo].[Notes_Tag] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_CreateTag]'
GO
CREATE PROCEDURE [dbo].[Notes_CreateTag]
		@foreignId int,
	@foreignType int,
	@tagName nvarchar(100),
	@tagId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT    @tagId= TagId
		FROM         Notes_Tag
		WHERE     (ForeignId = @foreignId) AND (ForeignType = @foreignType) AND (TagName = @tagName)

	IF(@tagId IS NULL)
	BEGIN    
		INSERT INTO Notes_Tag
							  (TagName, ForeignId, ForeignType)
		VALUES     (@tagName,@foreignId,@foreignType)

		SET @tagId=Scope_Identity()
	END
	

END





GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_RenameTag]'
GO
CREATE PROCEDURE [dbo].[Notes_RenameTag]
	@tagId int,
	@tagName nvarchar(100)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE Notes_Tag SET TagName=@tagName
		WHERE     (TagId = @tagId)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTags]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTags] 
     @repositoryName nvarchar(256),
	 @minCount int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT ReposTags.TagName, COUNT(ReposProcesses.ProcessId) AS ProcessCount, ReposTags.TagId
FROM  (SELECT ProcessId
         FROM  ProcessDefinition_Process AS ProcessDefinition_Process_1
         WHERE (ForeignId = @RepositoryId) AND (IsDeleted = 0)) AS ReposProcesses RIGHT OUTER JOIN
         Notes_AssignedTag ON ReposProcesses.ProcessId = Notes_AssignedTag.ForeignId RIGHT OUTER JOIN
             (SELECT Notes_Tag.TagId, Notes_Tag.TagName
            FROM  ProcessDefinition_Process INNER JOIN
                     Notes_Tag ON ProcessDefinition_Process.ProcessId = Notes_Tag.ForeignId
            WHERE (ProcessDefinition_Process.ForeignId = @RepositoryId)) AS ReposTags ON Notes_AssignedTag.TagId = ReposTags.TagId
GROUP BY ReposTags.TagName, ReposTags.TagId
ORDER BY ReposTags.TagName




END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_IsInProcessStructure]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_IsInProcessStructure] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	DECLARE @checkId int
	SET @checkId=
	(
	SELECT    TOP(1) ProcessStepId
FROM         ProcessDefinition_Step
WHERE     (ParentProcessId = @processId)
	)

		if(@checkId IS NULL)
	BEGIN
		SET @checkId=
		(
		SELECT    TOP(1) ProcessStepId
		FROM         ProcessDefinition_Step
		WHERE     (ChildProcessId = @processId)
		)

	END

	SELECT CASE WHEN @checkId IS NULL THEN 0 ELSE 1 END AS IsInProcessStructure

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositories]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositories] 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_Member.MemberRole, ProcessDefinition_Repository.RepositoryName
	FROM         ProcessDefinition_Member INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Member.UserId = @userId)
	ORDER BY ProcessDefinition_Repository.RepositoryName

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkedProcessesFromHistory]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkedProcessesFromHistory] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;



SELECT     ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId, ProcessDefinition_ProcessLinkHistory.ProcessId, ProcessDefinition_ProcessLinkHistory.SectionName, 
                      ProcessDefinition_ProcessLinkHistory.LinkUri, ProcessDefinition_ProcessLinkHistory.FullLinkUri, ProcessDefinition_ProcessLinkHistory.LinkText, 
                      ProcessDefinition_ProcessHistory.PrettyPostTitle, 
		ProcessDefinition_ProcessHistory.ProcessTitle, ProcessTypeId, LinksToProcessId, LinkType, SectionDirection
FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProcessLinkHistory.LinksToProcessId = ProcessDefinition_ProcessHistory.ProcessId
WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @processHistoryId) AND IsDeleted = 0

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_CopyDataFromType]'
GO
CREATE PROCEDURE [dbo].[Metadata_CopyDataFromType] 
		@fromTypeId int , 
	@fromForeignId int,
	@toTypeId int ,
	@toForeignId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

				DELETE FROM Metadata_Data
	WHERE (ForeignType = @toTypeId) AND (ForeignId = @toForeignId)

		INSERT INTO dbo.Metadata_Data(
      [MetadataId]
      ,[ForeignId]
      ,[ForeignType]
      ,[StringValue]
      ,[IntValue]
      ,[BoolValue]
      ,[DoubleValue]
      ,[DateValue]
      ,[IsDeleted]
      ,[DateChanged]
      ,[ChangedByUserId]
		)
	SELECT    [MetadataId], @toForeignId, @toTypeId, 
      [StringValue]
      ,[IntValue]
      ,[BoolValue]
      ,[DoubleValue]
      ,[DateValue]
      ,[IsDeleted]
      ,[DateChanged]
      ,[ChangedByUserId]
	FROM        Metadata_Data
	WHERE     (ForeignType = @fromTypeId) AND (ForeignId = @fromForeignId) AND (IsDeleted=0)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Metric]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Metric]
(
[MetricsSetId] [int] NOT NULL IDENTITY(1, 1),
[UserId] [int] NOT NULL,
[CreatedDateTime] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_Metric_CreatedDateTime] DEFAULT (getutcdate()),
[ProcessId] [int] NOT NULL,
[MajorVersion] [int] NOT NULL,
[MinorVersion] [int] NOT NULL,
[ProjectId] [int] NOT NULL CONSTRAINT [DF_ProcessDefinition_Metric_ProjectId] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Metric] on [dbo].[ProcessDefinition_Metric]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Metric] ADD CONSTRAINT [PK_ProcessDefinition_Metric] PRIMARY KEY CLUSTERED  ([MetricsSetId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Metric_UserId] on [dbo].[ProcessDefinition_Metric]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Metric_UserId] ON [dbo].[ProcessDefinition_Metric] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Metric_ProcessId] on [dbo].[ProcessDefinition_Metric]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Metric_ProcessId] ON [dbo].[ProcessDefinition_Metric] ([ProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Metric_MajorVersion] on [dbo].[ProcessDefinition_Metric]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Metric_MajorVersion] ON [dbo].[ProcessDefinition_Metric] ([MajorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Metric_MinorVersion] on [dbo].[ProcessDefinition_Metric]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Metric_MinorVersion] ON [dbo].[ProcessDefinition_Metric] ([MinorVersion])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Metric_ProjectId] on [dbo].[ProcessDefinition_Metric]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Metric_ProjectId] ON [dbo].[ProcessDefinition_Metric] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProjectProcessMetrics]'
GO

CREATE PROCEDURE [dbo].[Report_ProjectProcessMetrics] 
     @projectId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Account_User.DisplayName AS tf_User, Account_User.MemberEmailAddress AS tf_Email, ProcessDefinition_Metric.CreatedDateTime AS dtl_dateTime, 
                      ProcessDefinition_Process.ProcessTitle AS dd_Process, 
						CAST(ProcessDefinition_Metric.MinorVersion AS nvarchar) AS n_Revision, Metadata_MetadataField.ScreenLabel AS dd_Metric, 
                      COALESCE (Metadata_Data.StringValue, CAST(Metadata_Data.IntValue AS nvarchar), CAST(Metadata_Data.BoolValue AS nvarchar), 
                      CAST(Metadata_Data.DoubleValue AS nvarchar), CONVERT(nvarchar, Metadata_Data.DateValue, 106)) AS tf_Value, 
                      ProcessDefinition_Project.ProjectName AS dd_Project
FROM         ProcessDefinition_Metric INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_Metric.ProcessId = ProcessDefinition_Process.ProcessId INNER JOIN
                      Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId ON 
                      ProcessDefinition_Metric.MetricsSetId = Metadata_Data.ForeignId INNER JOIN
                      Account_User ON ProcessDefinition_Metric.UserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_Project ON ProcessDefinition_Metric.ProjectId = ProcessDefinition_Project.ProjectId
WHERE     (ProcessDefinition_Project.ProjectId = @projectId)
ORDER BY dtl_dateTime DESC
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_PublishedTag]'
GO
CREATE TABLE [dbo].[Notes_PublishedTag]
(
[PublishedTagId] [int] NOT NULL IDENTITY(1, 1),
[PublishId] [int] NOT NULL,
[TagId] [int] NOT NULL,
[TagName] [nvarchar] (100) NOT NULL,
[ForeignId] [int] NOT NULL CONSTRAINT [DF_Notes_PublishedTag_ForeignId] DEFAULT ((0)),
[ForeignType] [int] NOT NULL CONSTRAINT [DF_Notes_PublishedTag_ForeignType] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Notes_PublishedTag] on [dbo].[Notes_PublishedTag]'
GO
ALTER TABLE [dbo].[Notes_PublishedTag] ADD CONSTRAINT [PK_Notes_PublishedTag] PRIMARY KEY CLUSTERED  ([PublishedTagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedTag_PublishId] on [dbo].[Notes_PublishedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedTag_PublishId] ON [dbo].[Notes_PublishedTag] ([PublishId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedTag_TagId] on [dbo].[Notes_PublishedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedTag_TagId] ON [dbo].[Notes_PublishedTag] ([TagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedTag_ForeignId] on [dbo].[Notes_PublishedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedTag_ForeignId] ON [dbo].[Notes_PublishedTag] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedTag_ForeignType] on [dbo].[Notes_PublishedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedTag_ForeignType] ON [dbo].[Notes_PublishedTag] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE TABLE [dbo].[Notes_PublishedAssignedTag]
(
[PublishedAssignedTagId] [int] NOT NULL IDENTITY(1, 1),
[PublishId] [int] NOT NULL,
[AssignedTagId] [int] NOT NULL,
[TagId] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[AssignedByForeignId] [int] NOT NULL,
[AssignedByForeignType] [int] NOT NULL,
[AssignedDt] [datetime] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Notes_PublishedAssigned] on [dbo].[Notes_PublishedAssignedTag]'
GO
ALTER TABLE [dbo].[Notes_PublishedAssignedTag] ADD CONSTRAINT [PK_Notes_PublishedAssigned] PRIMARY KEY CLUSTERED  ([PublishedAssignedTagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_PublishId] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_PublishId] ON [dbo].[Notes_PublishedAssignedTag] ([PublishId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_AssignedTagId] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_AssignedTagId] ON [dbo].[Notes_PublishedAssignedTag] ([AssignedTagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_TagId] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_TagId] ON [dbo].[Notes_PublishedAssignedTag] ([TagId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_ForeignId] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_ForeignId] ON [dbo].[Notes_PublishedAssignedTag] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_ForeignType] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_ForeignType] ON [dbo].[Notes_PublishedAssignedTag] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_PublishedAssignedTag_AssignedByForeignId] on [dbo].[Notes_PublishedAssignedTag]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_PublishedAssignedTag_AssignedByForeignId] ON [dbo].[Notes_PublishedAssignedTag] ([AssignedByForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTagsByReposName]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTagsByReposName] 
	@repositoryName nvarchar(256),
	@lastPublished bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	IF(@lastPublished=0)
	BEGIN
	    SELECT     ISNULL(Notes_Tag.TagName,'untagged') AS TagName, COUNT(ProcessDefinition_Process.ProcessId) AS ProcessCount, ISNULL(Notes_Tag.TagId ,0) AS TagId
	    FROM         ProcessDefinition_Repository INNER JOIN
							 ProcessDefinition_Process ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Process.ForeignId LEFT OUTER JOIN
							 Notes_Tag INNER JOIN
							 Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId ON ProcessDefinition_Process.ProcessId = Notes_AssignedTag.ForeignId
	    WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName AND IsDeleted=0)
				AND Notes_Tag.ForeignType=144021
	    GROUP BY Notes_Tag.TagName, Notes_Tag.TagId
	    HAVING      (COUNT(ProcessDefinition_Process.ProcessId) > 0)
	    ORDER BY Notes_Tag.TagName
	END
    ELSE
    BEGIN 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    	   DECLARE @lastPublishedId int
	   SELECT @lastPublishedId=MAX(PublishId)
	   FROM  ProcessDefinition_Publish
	   WHERE (RepositoryId = @RepositoryId)

	    SELECT     ISNULL(Notes_PublishedTag.TagName,'untagged') AS TagName, COUNT(ProcessDefinition_Process.ProcessId) AS ProcessCount, ISNULL(Notes_PublishedTag.TagId ,0) AS TagId
	    FROM         ProcessDefinition_Repository INNER JOIN
							 ProcessDefinition_Process ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Process.ForeignId LEFT OUTER JOIN
							 Notes_PublishedTag INNER JOIN
							 Notes_PublishedAssignedTag ON Notes_PublishedTag.TagId = Notes_PublishedAssignedTag.TagId ON ProcessDefinition_Process.ProcessId = Notes_PublishedAssignedTag.ForeignId
	    WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName AND IsDeleted=0)
				AND Notes_PublishedTag.PublishId=@lastPublishedId AND Notes_PublishedAssignedTag.PublishId=@lastPublishedId
	    GROUP BY Notes_PublishedTag.TagName, Notes_PublishedTag.TagId
	    HAVING      (COUNT(ProcessDefinition_Process.ProcessId) > 0)
	    ORDER BY Notes_PublishedTag.TagName




    END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesLinkUsageFromHistory]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesLinkUsageFromHistory]
      @processhistoryid INT, @publishid INT
WITH ENCRYPTION AS
     BEGIN
                           SET NOCOUNT ON;
         SELECT ProcessId,
                SectionName,
                LinkText,
                ProcessTitle,
                PrettyPostTitle,
                DescriptionSnippet,
                ProcessTypeId,
                LinkType,
                SectionDirection
         FROM
             (
             SELECT LinksFROM.ProcessId,
                    LinksFROM.SectionName,
                    LinksFROM.LinkText,
                    LinksFROM.ProcessTitle,
                    LinksFROM.PrettyPostTitle,
                    LinksFROM.DescriptionSnippet,
                    LinksFROM.ProcessTypeId,
                    LinksFROM.LinkType,
                    LinksFROM.SectionDirection
             FROM
                 (
                  SELECT ProcessDefinition_PublishProcess.ProcessHistoryId,
                         ProcessDefinition_ProcessLinkHistory.ProcessId,
                         ProcessDefinition_ProcessLinkHistory.SectionName,
                         ProcessDefinition_ProcessLinkHistory.LinkText,
                         ProcessDefinition_ProcessHistory.ProcessTitle,
                         ProcessDefinition_ProcessLinkHistory.LinksToProcessId,
                         ProcessDefinition_ProcessHistory.PrettyPostTitle,
                         ProcessDefinition_ProcessHistory.DescriptionSnippet,
                         ProcessDefinition_ProcessHistory.ProcessTypeId,
                         ProcessDefinition_ProcessLinkHistory.LinkType,
                         ProcessDefinition_ProcessLinkHistory.SectionDirection
                  FROM ProcessDefinition_PublishProcess
                       INNER JOIN ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_PublishProcess.ProcessHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessHistoryId
                  INNER JOIN ProcessDefinition_ProcessHistory ON ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
                  WHERE(ProcessDefinition_PublishProcess.PublishId = @publishid)
                       AND (ProcessDefinition_ProcessHistory.IsDeleted = 0)
                 ) AS LinksFROM
                 INNER JOIN
                           (
                            SELECT ProcessDefinition_PublishProcess_1.ProcessHistoryId,
                                   ProcessDefinition_PublishProcess_1.ProcessId
                            FROM ProcessDefinition_PublishProcess AS ProcessDefinition_PublishProcess_1
                                 INNER JOIN ProcessDefinition_ProcessLinkHistory AS ProcessDefinition_ProcessLinkHistory_1 ON ProcessDefinition_PublishProcess_1.ProcessHistoryId = ProcessDefinition_ProcessLinkHistory_1.ProcessHistoryId
                            WHERE(ProcessDefinition_PublishProcess_1.PublishId = @publishid)
                                 AND (ProcessDefinition_PublishProcess_1.ProcessHistoryId = @processhistoryid)
                           ) AS LinksTo ON LinksFROM.LinksToProcessId = LinksTo.ProcessId
             GROUP BY LinksFROM.ProcessId,
                      LinksFROM.SectionName,
                      LinksFROM.LinkText,
                      LinksFROM.ProcessTitle,
                      LinksFROM.LinksToProcessId,
                      LinksFROM.PrettyPostTitle,
                      LinksFROM.DescriptionSnippet,
                      LinksFROM.ProcessTypeId,
                      LinksFROM.LinkType,
                      LinksFROM.SectionDirection
             UNION
             SELECT FromProcess.ProcessId,
                    'Steps' AS SectionName,
                    FromProcess.StepName AS LinkText,
                    FromProcess.ProcessTitle,
                    FromProcess.PrettyPostTitle,
                    FromProcess.DescriptionSnippet,
                    FromProcess.ProcessTypeId,
                    CASE
                        WHEN((FromProcess.StepType&4) > 0)
                        THEN 4
                        ELSE 0
                    END AS LinkType,
                    '' AS SectionDirection
             FROM
                 (
                  SELECT ProcessDefinition_StepHistory.ChildProcessId,
                         ProcessDefinition_ProcessHistory.ProcessId,
                         ProcessDefinition_StepHistory.StepName,
                         ProcessDefinition_ProcessHistory.ProcessTitle,
                         ProcessDefinition_ProcessHistory.PrettyPostTitle,
                         ProcessDefinition_ProcessHistory.DescriptionSnippet,
                         ProcessDefinition_ProcessHistory.ProcessTypeId,
                         ProcessDefinition_StepHistory.StepType
                  FROM ProcessDefinition_StepHistory
                       INNER JOIN ProcessDefinition_PublishProcess ON ProcessDefinition_StepHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
                  INNER JOIN ProcessDefinition_ProcessHistory ON ProcessDefinition_StepHistory.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
                  WHERE(ProcessDefinition_PublishProcess.PublishId = @publishid)
                 ) AS FromProcess
                 INNER JOIN
                           (
SELECT ProcessHistoryId, ProcessId
FROM  ProcessDefinition_PublishProcess AS ProcessDefinition_PublishProcess_1 WHERE(ProcessDefinition_PublishProcess_1.PublishId = @publishid)
                                 AND (ProcessDefinition_PublishProcess_1.ProcessHistoryId = @processhistoryid)
                           ) AS LinksTo ON FromProcess.ChildProcessId = LinksTo.ProcessId
             ) AS Links
         ORDER BY Links.SectionName,
                  Links.ProcessTitle;
     END;
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CopyUsageLinkData]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_CopyUsageLinkData] 
		@fromProcessHistoryId int,
	@toProcessId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	
	
				DELETE FROM Metadata_Data
	WHERE (ForeignType = 20) AND (ForeignId IN (SELECT ProcessLinkDataId
		FROM ProcessDefinition_ProcessLinkData
		WHERE ProcessId = @toProcessId))

		INSERT INTO dbo.Metadata_Data(
      [MetadataId]
      ,[ForeignId]
      ,[ForeignType]
      ,[StringValue]
      ,[IntValue]
      ,[BoolValue]
      ,[DoubleValue]
      ,[DateValue]
      ,[IsDeleted]
      ,[DateChanged]
      ,[ChangedByUserId]
		)
SELECT     Metadata_Data.MetadataId, 
		ProcessDefinition_ProcessLinkData.ProcessLinkDataId,
		20, 
		Metadata_Data.StringValue, 
		Metadata_Data.IntValue, 
		Metadata_Data.BoolValue, 
		Metadata_Data.DoubleValue, 
        Metadata_Data.DateValue, 
		Metadata_Data.IsDeleted, 
		Metadata_Data.DateChanged, 
		Metadata_Data.ChangedByUserId
FROM         Metadata_Data INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON Metadata_Data.ForeignId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId INNER JOIN
                      ProcessDefinition_ProcessLinkData ON ProcessDefinition_ProcessLinkHistory.LinkUid = ProcessDefinition_ProcessLinkData.LinkUid
WHERE     (Metadata_Data.ForeignType = 21) AND (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @fromProcessHistoryId)
	AND (IsDeleted=0)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_StepFidelity]'
GO
CREATE PROCEDURE [dbo].[Report_StepFidelity] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

    	SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectName, 
		ProcessDefinition_ProjectPlanTask.TaskName, 
	CASE 
		WHEN TaskIsRemoved = 1 AND TaskOptional = 1 THEN 'Removed, optional' 
		WHEN TaskIsRemoved = 1 AND TaskOptional = 0 THEN 'Removed, non optional' 
		WHEN TaskType = 2 OR TaskType = 10 THEN 'Added' 
		WHEN TaskType = 16 THEN 'Alternative process chosen' 
			END AS Issue, 
		ProcessDefinition_ProjectPlanTask.RemovalReason,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId as nvarchar(12))+'|'+CAST(ProcessDefinition_ProjectPlanTask.ParentTaskId as nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
WHERE     ((ProcessDefinition_ProjectPlanTask.TaskType = 2) OR
                      (ProcessDefinition_ProjectPlanTask.TaskType = 10) OR
                      (ProcessDefinition_ProjectPlanTask.TaskIsRemoved = 1))
			AND ProcessDefinition_ProjectPlan.ProjectId = @projectId
AND
( (@projectPlanId IS NULL) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetBrowseSummary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetBrowseSummary] 
	@repositoryName nvarchar(256),	
	@projectId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @latestProcess datetime, @lastUpdate datetime, @assignedTo datetime, @assignedBy datetime, @lastViewed datetime

	 SET @latestProcess=
	(SELECT    TOP(1) DateCreated
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId AND IsDeleted=0)
	ORDER BY DateCreated DESC)

	 SET @lastUpdate=
	(SELECT    TOP(1) DateUpdated
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId AND IsDeleted=0)
	ORDER BY DateUpdated DESC)



	SET @lastViewed=
	(
	SELECT    TOP(1) ProcessDefinition_Access.DateAccessed
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Access ON ProcessDefinition_Process.ProcessId = ProcessDefinition_Access.ProcessId
	WHERE     (ProcessDefinition_Access.UserId = @userId) AND 
		(ProcessDefinition_Process.ForeignId = @RepositoryId) AND IsDeleted=0
	ORDER BY ProcessDefinition_Access.DateAccessed DESC
	)

	SELECT @latestProcess AS LatestProcess, @lastUpdate AS LastUpdate,@lastViewed AS LastViewed

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryChurn]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryChurn]
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @dtNow DateTime
	SET @dtNow=GetUtcDate()
	SELECT     COUNT(ProcessDefinition_Process.ProcessId) AS ProcessCount, 
			CASE WHEN DATEDIFF(month, ProcessDefinition_Process.DateUpdated, @dtNow) >= 12 THEN 13 ELSE DATEDIFF(month, ProcessDefinition_Process.DateUpdated, @dtNow) END AS UpdatedMonth
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)  AND IsDeleted = 0
	GROUP BY DATEDIFF(month, ProcessDefinition_Process.DateUpdated, @dtNow)
	ORDER BY UpdatedMonth DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetImportDataIds]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetImportDataIds] 
	@processId int, 
	@uniqueFieldId uniqueidentifier,
	@uniqueLinkId varchar(50)	
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	DECLARE @processHistoryId INT
	DECLARE @processLinkHistoryId INT
	DECLARE @linkToProcessId INT
	
	SELECT    @processHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId, 
				@processLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId,
				@linkToProcessId = ProcessDefinition_ProcessLinkHistory.LinksToProcessId
	FROM         ProcessDefinition_ProcessHistory INNER JOIN
						  ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessHistoryId
	WHERE     (ProcessDefinition_ProcessHistory.ProcessId = @processId) AND (ProcessDefinition_ProcessHistory.IsLatestVersion = 1) AND 
						  (ProcessDefinition_ProcessLinkHistory.LinkUid = @uniqueLinkId)
	
		SELECT    @processHistoryId = ProcessHistoryId
	FROM         ProcessDefinition_ProcessHistory 
	WHERE ProcessId = @linkToProcessId AND (ProcessDefinition_ProcessHistory.IsLatestVersion = 1)


	DECLARE @metadataId INT
	SELECT  @metadataId =   MetadataId
	FROM         Metadata_MetadataField
	WHERE     (ForeignType = 19) AND (ForeignId = @processHistoryId) AND UniqueId = @uniqueFieldId

	SELECT @processHistoryId AS ProcessHistoryId, @processLinkHistoryId AS ProcessLinkHistoryId, @metadataId AS MetadataId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetAllAssignedTagsByNameAndType]'
GO
CREATE FUNCTION [dbo].[Notes_GetAllAssignedTagsByNameAndType]
(	
	@tagName nvarchar(100),
	@foreignType int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(
	SELECT     Notes_AssignedTag.AssignedTagId, Notes_AssignedTag.ForeignId
	FROM         Notes_AssignedTag INNER JOIN
						  Notes_Tag ON Notes_AssignedTag.TagId = Notes_Tag.TagId
	WHERE     (Notes_Tag.TagName = @tagName) AND (Notes_AssignedTag.ForeignType = @foreignType)
)

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesByTag]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesByTag]
	@repositoryName nvarchar(256),
	@tagName nvarchar(256),
	@userId int,
	@usePublished bit
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	IF(@usePublished=0)
	BEGIN
	    SELECT     ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.DescriptionSnippet,
		    dbo.ProcessDefinition_HasProcessAccess(ProcessId, @userId) AS HasPostAccess
	    FROM         ProcessDefinition_Repository INNER JOIN
							 ProcessDefinition_Process ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Process.ForeignId LEFT OUTER JOIN
							 Notes_Tag INNER JOIN
							 Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId ON ProcessDefinition_Process.ProcessId = Notes_AssignedTag.ForeignId
	    WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted=0 AND
	    (
		    (Notes_Tag.TagName = @tagName) 
			    OR 
		    ((Notes_Tag.TagName IS NULL) AND (@tagName='untagged'))
	    )
	    ORDER BY Notes_Tag.TagName, ProcessDefinition_Process.ProcessTitle
	END
	ELSE
	BEGIN

	   DECLARE @repositoryId int
	   SET @repositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	   DECLARE @lastPublishedId int

	   SELECT @lastPublishedId=MAX(PublishId)
	   FROM  ProcessDefinition_Publish
	   WHERE (RepositoryId = @repositoryId)

	    SELECT     ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.DescriptionSnippet,
		    dbo.ProcessDefinition_HasProcessAccess(ProcessDefinition_ProcessHistory.ProcessId, @userId) AS HasPostAccess
FROM  ProcessDefinition_ProcessHistory INNER JOIN
         ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId INNER JOIN
         ProcessDefinition_Repository ON ProcessDefinition_ProcessHistory.ForeignId = ProcessDefinition_Repository.RepositoryId LEFT OUTER JOIN
         Notes_PublishedTag INNER JOIN
         Notes_PublishedAssignedTag ON Notes_PublishedTag.TagId = Notes_PublishedAssignedTag.TagId ON ProcessDefinition_PublishProcess.ProcessId = Notes_PublishedAssignedTag.ForeignId	    
	    WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted=0 AND
	    (
		    (Notes_PublishedTag.TagName = @tagName) 
			    OR 
		    ((Notes_PublishedTag.TagName IS NULL) AND (@tagName='untagged'))
	    )
	    AND
	    (
	    Notes_PublishedAssignedTag.PublishId=@lastPublishedId AND Notes_PublishedTag.PublishId=@lastPublishedId
	    )
	    ORDER BY Notes_PublishedTag.TagName, ProcessDefinition_ProcessHistory.ProcessTitle

	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_ChangedLinkNames]'
GO
CREATE PROCEDURE [dbo].[Review_ChangedLinkNames] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_Process.ProcessTitle AS tf_Process,'~/' + ProcessDefinition_Process.PrettyPostTitle AS link_Process,
						  ProcessDefinition_ProcessLink.SectionName AS dd_Section, 
						ProcessDefinition_ProcessLink.LinkText AS tf_LinkText, ProcessDefinition_Process_1.ProcessTitle AS tf_ToProcess
	FROM         ProcessDefinition_Process INNER JOIN
						  Account_User ON ProcessDefinition_Process.UserId = Account_User.UserId INNER JOIN
						  ProcessDefinition_ProcessLink ON ProcessDefinition_Process.ProcessId = ProcessDefinition_ProcessLink.ProcessId INNER JOIN
						  ProcessDefinition_Process AS ProcessDefinition_Process_1 ON ProcessDefinition_ProcessLink.LinksToProcessId = ProcessDefinition_Process_1.ProcessId
	WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId) AND (ProcessDefinition_ProcessLink.LinkText<>ProcessDefinition_Process_1.ProcessTitle)
	UNION
	SELECT      ProcessDefinition_Process.ProcessTitle AS tf_Process,'~/' + ProcessDefinition_Process.PrettyPostTitle AS link_Process,
				'Steps' AS dd_Section,
				ProcessDefinition_Step.StepName AS tf_LinkText,
				ProcessDefinition_Process_1.ProcessTitle AS tf_ToProcess
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Step ON ProcessDefinition_Process.ProcessId = ProcessDefinition_Step.ParentProcessId INNER JOIN
						  ProcessDefinition_Process AS ProcessDefinition_Process_1 ON ProcessDefinition_Step.ChildProcessId = ProcessDefinition_Process_1.ProcessId
		WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId) AND (ProcessDefinition_Step.StepName<>ProcessDefinition_Process_1.ProcessTitle)
	ORDER BY tf_Process,dd_Section,tf_LinkText


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetAllTagsByForeignIdType]'
GO
CREATE PROCEDURE [dbo].[Notes_GetAllTagsByForeignIdType]
	@TagForeignId int,
	@TagForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     TagId, TagName
	FROM         Notes_Tag
	WHERE     ((ForeignId = @TagForeignId) OR (@TagForeignId IS NULL)) AND (ForeignType = @TagForeignType)
	ORDER BY TagName
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_CreateAssignedTag]'
GO
CREATE PROCEDURE [dbo].[Notes_CreateAssignedTag]
		@foreignId int,
	@foreignType int,
	@AssignedByForeignId int,
	@AssignedByForeignType int,
	@tagName nvarchar(100),
	@AssignedTagId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @thisReposId int
	SELECT @thisReposId=ForeignId
	FROM  ProcessDefinition_Process
	WHERE (ProcessId = @foreignId)

	DECLARE @tagId int
	SELECT @tagId=Notes_Tag.TagId
	FROM  Notes_Tag INNER JOIN
			 ProcessDefinition_Process ON Notes_Tag.ForeignId = ProcessDefinition_Process.ProcessId
	WHERE (ProcessDefinition_Process.ForeignId = @thisReposId) AND (Notes_Tag.TagName = @tagName)


	IF (@tagId IS NULL)
	BEGIN
				INSERT INTO Notes_Tag (TagName, ForeignId, ForeignType) VALUES (@tagName, @foreignId, @foreignType)
		SET @tagId = SCOPE_IDENTITY()
	END

	exec Notes_CreateAssignedTagWithTagId 	@foreignId,	@foreignType,@AssignedByForeignId,@AssignedByForeignType,@tagId,@AssignedTagId OUTPUT

END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetTag]'
GO
CREATE PROCEDURE [dbo].[Notes_GetTag]
		@tagId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		SELECT     TagName
	FROM         Notes_Tag
	WHERE     (TagId = @tagId)

			SELECT     ForeignId, ForeignType, '' AS ItemName
	FROM         Notes_AssignedTag
	WHERE     (TagId = @tagId)
	ORDER BY ItemName

		SELECT     Notes_Tag_1.TagName, Notes_AssignedTag_1.TagId, COUNT(Notes_AssignedTag_1.AssignedTagId) AS TagCount
	FROM         Notes_Tag AS Notes_Tag_1 INNER JOIN
						  Notes_AssignedTag AS Notes_AssignedTag_1 ON Notes_Tag_1.TagId = Notes_AssignedTag_1.TagId INNER JOIN
							  (SELECT     Notes_AssignedTag.ForeignId, Notes_AssignedTag.ForeignType
								FROM          Notes_Tag INNER JOIN
													   Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId
								WHERE      (Notes_Tag.TagId = @tagId)) AS LinkedItems ON Notes_AssignedTag_1.ForeignId = LinkedItems.ForeignId AND 
						  Notes_AssignedTag_1.ForeignType = LinkedItems.ForeignType
	GROUP BY Notes_Tag_1.TagName, Notes_AssignedTag_1.TagId
	HAVING      (Notes_AssignedTag_1.TagId <> @tagId)
	ORDER BY Notes_Tag_1.TagName

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO


GO
PRINT N'Creating [dbo].[ProcessDefinition_Discussion]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Discussion]
(
[DiscussionId] [int] NOT NULL IDENTITY(1, 1),
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[UserId] [int] NOT NULL,
[DiscussionText] [nvarchar] (max) NOT NULL,
[CreatedDateTime] [datetime] NOT NULL CONSTRAINT [DF_ProcessDefinition_Discussion_CreatedDateTime] DEFAULT (getutcdate())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Discussion] on [dbo].[ProcessDefinition_Discussion]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Discussion] ADD CONSTRAINT [PK_ProcessDefinition_Discussion] PRIMARY KEY CLUSTERED  ([DiscussionId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Discussion_ForeignId] on [dbo].[ProcessDefinition_Discussion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Discussion_ForeignId] ON [dbo].[ProcessDefinition_Discussion] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Discussion_ForeignType] on [dbo].[ProcessDefinition_Discussion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Discussion_ForeignType] ON [dbo].[ProcessDefinition_Discussion] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_Discussion_UserId] on [dbo].[ProcessDefinition_Discussion]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_Discussion_UserId] ON [dbo].[ProcessDefinition_Discussion] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateDiscussion]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateDiscussion]
(
     @foreignId int,
      @foreignType int,
      @userId int,
      @DiscussionText nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO ProcessDefinition_Discussion
      (
            ForeignId, 
            ForeignType, 
            UserId, 
            DiscussionText

      ) VALUES (
            @foreignId, 
            @foreignType, 
            @userId, 
            @DiscussionText
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()

SELECT     @newId AS NewDiscussionId, Account_User.DisplayName, Account_User.MemberEmailAddress, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
                      ProcessDefinition_ProcessHistory.ProcessTitle
FROM         Account_User INNER JOIN
                      ProcessDefinition_ProcessHistory ON Account_User.UserId = ProcessDefinition_ProcessHistory.UserId
WHERE     (ProcessDefinition_ProcessHistory.ProcessHistoryId = @foreignId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetTagAutocompleteListForForeignIdAssignor]'
GO
CREATE PROCEDURE [dbo].[Notes_GetTagAutocompleteListForForeignIdAssignor] 
	@prefix nvarchar(100),
	@foreignId int,
	@foreignType int,
	@AssignedByForeignId int,
	@AssignedByForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @prefixLen int
	SET @prefixLen=LEN(@prefix)

	SELECT     Notes_Tag.TagName
	FROM         Notes_Tag INNER JOIN
						  Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId
	WHERE     (LEFT(Notes_Tag.TagName, @prefixLen) = @prefix) AND (Notes_AssignedTag.ForeignId = @foreignId) AND (Notes_AssignedTag.ForeignType = @foreignType) AND 
						  (Notes_AssignedTag.AssignedByForeignId = @AssignedByForeignId) AND (Notes_AssignedTag.AssignedByForeignType = @AssignedByForeignType)
	ORDER BY LEN(Notes_Tag.TagName), Notes_Tag.TagName
END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetStepDefinitionVersion]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetStepDefinitionVersion] 
	@ParentProcessId int,
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	
	DECLARE @CorrectProcessHistoryId int
	SELECT @CorrectProcessHistoryId =  ProcessHistoryId
	FROM ProcessDefinition_ProcessHistory
	WHERE   (ProcessDefinition_ProcessHistory.ProcessId = @ParentProcessId) AND
		 ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))

	SELECT StepDefinitionVersion
	FROM  ProcessDefinition_ProcessHistory
	WHERE ProcessHistoryId=@CorrectProcessHistoryId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO


GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteDiscussion]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteDiscussion]
(
     @DiscussionId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     DELETE FROM ProcessDefinition_Discussion WHERE DiscussionId=@DiscussionId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UploadedFile]'
GO
CREATE TABLE [dbo].[ProcessDefinition_UploadedFile]
(
[UploadedFileId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[UploadedFilename] [nvarchar] (400) NOT NULL,
[UploadedFileUrlOffset] [nvarchar] (400) NOT NULL,
[FileContent] [nvarchar] (max) NULL,
[ContentSnippet] [nvarchar] (1024) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_UploadedFile] on [dbo].[ProcessDefinition_UploadedFile]'
GO
ALTER TABLE [dbo].[ProcessDefinition_UploadedFile] ADD CONSTRAINT [PK_ProcessDefinition_UploadedFile] PRIMARY KEY CLUSTERED  ([UploadedFileId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_UploadedFile_UploadedFilename] on [dbo].[ProcessDefinition_UploadedFile]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_UploadedFile_UploadedFilename] ON [dbo].[ProcessDefinition_UploadedFile] ([UploadedFilename])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StoreUploadedFile]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_StoreUploadedFile] 
	 @repositoryName nvarchar(256),
	@UploadedFilename nvarchar(400),
	@UploadedFileUrlOffset nvarchar(400),
	@FileContent nvarchar(max),
	@ContentSnippet nvarchar(104)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @UploadedFileId int

	SELECT     @UploadedFileId=UploadedFileId
	FROM         ProcessDefinition_UploadedFile
	WHERE     ((UploadedFilename = @UploadedFilename) AND (RepositoryId=@RepositoryId))

	IF(@UploadedFileId IS NULL)
	BEGIN

		INSERT INTO ProcessDefinition_UploadedFile
						  (RepositoryId, UploadedFilename, UploadedFileUrlOffset, FileContent,ContentSnippet)
		VALUES     (@RepositoryId,@UploadedFilename,@UploadedFileUrlOffset,@FileContent,@ContentSnippet)
	END
	ELSE
	BEGIN
		UPDATE    ProcessDefinition_UploadedFile
		SET        FileContent = @FileContent,ContentSnippet=@ContentSnippet
		WHERE     (UploadedFileId = @UploadedFileId)
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetTagCloud]'
GO
CREATE PROCEDURE [dbo].[Notes_GetTagCloud]
		@AssignedByForeignId int,
	@AssignedByForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT X.TagId, X.TagName, X.TagCount FROM
	(
	SELECT     Notes_Tag.TagId, Notes_Tag.TagName, COUNT(Notes_AssignedTag.AssignedTagId) AS TagCount
	FROM         Notes_AssignedTag INNER JOIN
						  Notes_Tag ON Notes_AssignedTag.TagId = Notes_Tag.TagId
	WHERE      (Notes_AssignedTag.AssignedByForeignId = @AssignedByForeignId)
					AND
				(Notes_AssignedTag.AssignedByForeignType = @AssignedByForeignType)
	GROUP BY Notes_Tag.TagId, Notes_Tag.TagName
	) AS X
	WHERE X.TagCount>0
	ORDER BY X.TagName
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetHistoryStepDefinitionVersion]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetHistoryStepDefinitionVersion] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	SELECT StepDefinitionVersion
	FROM  ProcessDefinition_ProcessHistory
	WHERE ProcessHistoryId=@processHistoryId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProjectLibraryMetrics]'
GO
CREATE PROCEDURE [dbo].[Report_ProjectLibraryMetrics] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    

SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectPlanName, ParentTask.TaskName AS dd_ParentTaskName, 
ProcessDefinition_ProjectPlanTask.TaskName AS dd_TaskName, ProcessDefinition_ProcessHistory.MinorVersion AS Revision, 
'' AS tf_Section,
	'' AS ProcessTitle, Metadata_MetadataField.ScreenLabel AS dd_DataLabel, 
                      COALESCE (Metadata_Data.StringValue, CAST(Metadata_Data.IntValue AS varchar), CASE WHEN Metadata_Data.BoolValue = 1 THEN 'Yes' WHEN Metadata_Data.BoolValue = 0 THEN 'No' ELSE NULL END, 
                      CAST(Metadata_Data.DoubleValue AS varchar), CAST(Metadata_Data.DateValue AS varchar)) AS [Value],  Metadata_Data.DateChanged AS dtl_DateEntered, Account_User.DisplayName AS dd_UserName,
		'~/Project/{0:scramble,pPl}/Framed/{1}|'+CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId as nvarchar(12))+'|'+CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId as nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlan INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                      Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = Metadata_Data.ForeignId INNER JOIN
                      Account_User ON Metadata_Data.ChangedByUserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId LEFT OUTER JOIN
                      ProcessDefinition_ProjectPlanTask AS ParentTask ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ParentTask.ProjectPlanTaskId
WHERE     (Metadata_Data.ForeignType = 15) AND (ProcessDefinition_ProjectPlan.ProjectId = @projectId)
AND
( (ISNULL(@projectPlanId,0)=0) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectPlanName, ParentTask.TaskName AS dd_ParentTaskName, 
                      ProcessDefinition_ProjectPlanTask.TaskName AS dd_TaskName, ProcessDefinition_ProcessHistory.MinorVersion AS Revision, 
						ProcessDefinition_ProcessLinkHistory.SectionName AS tf_Section,
                      ProcessDefinition_ProcessHistory.ProcessTitle, Metadata_MetadataField.ScreenLabel AS dd_DataLabel, COALESCE (Metadata_Data.StringValue, 
                      CAST(Metadata_Data.IntValue AS varchar), CASE WHEN Metadata_Data.BoolValue = 1 THEN 'Yes' WHEN Metadata_Data.BoolValue = 0 THEN 'No' ELSE NULL END, 
                      CAST(Metadata_Data.DoubleValue AS varchar), CAST(Metadata_Data.DateValue AS varchar)) AS Value, Metadata_Data.DateChanged AS dtl_DateEntered, 
                      Account_User.DisplayName AS dd_UserName, '~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanId AS nvarchar(12)) 
                      + '|' + CAST(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS nvarchar(12)) AS flink_Link 
FROM         ProcessDefinition_ProjectPlan INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                      Account_User INNER JOIN
                      Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId ON 
                      Account_User.UserId = Metadata_Data.ChangedByUserId INNER JOIN
                      ProcessDefinition_ProjectPlanTaskLink ON Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskLink.TaskId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId LEFT OUTER JOIN
                      ProcessDefinition_ProjectPlanTask AS ParentTask ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ParentTask.ProjectPlanTaskId
WHERE     (Metadata_Data.ForeignType = 14) AND (ProcessDefinition_ProjectPlan.ProjectId = @projectId)
AND
( (ISNULL(@projectPlanId,0)=0) OR (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId))

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetDiscussion]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetDiscussion]
(
     @DiscussionId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     SELECT ForeignId, 
            ForeignType, 
            UserId, 
            DiscussionText, 
            CreatedDateTime
            FROM ProcessDefinition_Discussion WHERE DiscussionId=@DiscussionId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessParents]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessParents] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.PrettyPostTitle, 
						  ProcessDefinition_Process.DescriptionSnippet
	FROM         ProcessDefinition_Step INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_Step.ParentProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_Step.ChildProcessId = @processId)
	ORDER BY ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ResetUploadedFiles]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ResetUploadedFiles] 
	 @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DELETE
	FROM         ProcessDefinition_UploadedFile
	WHERE     (RepositoryId=@RepositoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetTagAutocompleteListForForeignId]'
GO
CREATE PROCEDURE [dbo].[Notes_GetTagAutocompleteListForForeignId] 
	@prefix nvarchar(100),
	@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @prefixLen int
	SET @prefixLen=LEN(@prefix)

	SELECT     Notes_Tag.TagName
	FROM         Notes_Tag INNER JOIN
						  Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId
	WHERE     (LEFT(Notes_Tag.TagName, @prefixLen) = @prefix) AND (Notes_AssignedTag.ForeignId = @foreignId) AND (Notes_AssignedTag.ForeignType = @foreignType)
	ORDER BY LEN(Notes_Tag.TagName), Notes_Tag.TagName

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetDiscussions]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetDiscussions]
	@foreignId int, 
    @foreignType int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	
	SELECT     ProcessDefinition_Discussion.DiscussionId, ProcessDefinition_Discussion.UserId, ProcessDefinition_Discussion.DiscussionText, 
						  ProcessDefinition_Discussion.CreatedDateTime, Account_User.DisplayName, Account_User.MemberEmailAddress, CONVERT(nvarchar(30), 
						  ProcessDefinition_Discussion.CreatedDateTime, 106) AS CreatedDateTimeText, ProcessDefinition_ProcessHistory.MinorVersion
	FROM         ProcessDefinition_Discussion INNER JOIN
						  Account_User ON ProcessDefinition_Discussion.UserId = Account_User.UserId INNER JOIN
						  ProcessDefinition_ProcessHistory ON ProcessDefinition_Discussion.ForeignId = ProcessDefinition_ProcessHistory.ProcessHistoryId
	WHERE     (ProcessDefinition_Discussion.ForeignType = @foreignType) AND (ProcessDefinition_ProcessHistory.ProcessId = @foreignId)
	ORDER BY ProcessDefinition_Discussion.CreatedDateTime DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_DeleteTag]'
GO
CREATE PROCEDURE [dbo].[Notes_DeleteTag]
	@tagId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DELETE FROM Notes_AssignedTag
		WHERE     (TagId = @tagId)

	DELETE FROM Notes_Tag
		WHERE     (TagId = @tagId)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Error_Log]'
GO
CREATE TABLE [dbo].[Error_Log]
(
[ErrorId] [int] NOT NULL IDENTITY(1, 1),
[To] [varchar] (255) NULL,
[From] [varchar] (255) NULL,
[Subject] [varchar] (255) NULL,
[Body] [text] NULL,
[SentDt] [datetime] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Error_CreateLog]'
GO
CREATE PROCEDURE [dbo].[Error_CreateLog] 
	(
	@To varchar(255),
	@From varchar(255),
	@Subject varchar(255),
	@Body text
	)
WITH ENCRYPTION AS

INSERT INTO Error_Log([To], [From], Subject, Body, SentDt)
VALUES (@To, @From, @Subject, @Body, GetUtcDate())

	RETURN
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateRepository]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateRepository] 
	@repositoryName nvarchar(256), 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @ret int

	INSERT INTO ProcessDefinition_Repository
						  (RepositoryName)
	VALUES     (@repositoryName)

	SET @ret=Scope_Identity()

	INSERT INTO ProcessDefinition_Member
                      (RepositoryId, UserId, MemberRole)
	VALUES     (@ret,@userId, 4)
	
	RETURN @ret

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessByName]'
GO
 

CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessByName]
(
     @PostName nvarchar(256),
	@repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.ForeignType, ProcessDefinition_Process.ForeignId, ProcessDefinition_Process.DateCreated, 
						  ProcessDefinition_Process.ProcessDescription, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.IsPublished, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Process.ProcessTitle = @PostName) AND (ProcessDefinition_Repository.RepositoryName = @repositoryName)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetAssignedTagsByAssignor]'
GO
CREATE PROCEDURE [dbo].[Notes_GetAssignedTagsByAssignor]
		@foreignId int,
	@foreignType int,
	@AssignedByForeignId int,
	@AssignedByForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	SELECT     Notes_Tag.TagName, Notes_AssignedTag.AssignedTagId, TagUsage.AssignedTagCount, Notes_AssignedTag.TagId
	FROM         Notes_AssignedTag INNER JOIN
						  Notes_Tag ON Notes_AssignedTag.TagId = Notes_Tag.TagId INNER JOIN
							  (SELECT     TagId, COUNT(AssignedTagId) AS AssignedTagCount
FROM         Notes_AssignedTag AS Notes_AssignedTag_1
WHERE     (AssignedByForeignId = @AssignedByForeignId) AND (AssignedByForeignType = @AssignedByForeignType)
GROUP BY TagId) AS TagUsage ON Notes_AssignedTag.TagId = TagUsage.TagId
	WHERE     (Notes_AssignedTag.ForeignId = @foreignId) AND (Notes_AssignedTag.ForeignType = @foreignType)
	AND (Notes_AssignedTag.AssignedByForeignId = @AssignedByForeignId) AND (Notes_AssignedTag.AssignedByForeignType = @AssignedByForeignType)
	ORDER BY Notes_Tag.TagName


END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProcessLibraryMetrics]'
GO
CREATE PROCEDURE [dbo].[Report_ProcessLibraryMetrics] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    
DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectPlanName, ParentTask.TaskName AS dd_ParentTaskName, 
                      ProcessDefinition_ProjectPlanTask.TaskName AS dd_TaskName, ProcessDefinition_ProcessHistory.MinorVersion AS Revision, '' AS ProcessTitle, 
                      Metadata_MetadataField.ScreenLabel AS dd_DataLabel, COALESCE (Metadata_Data.StringValue, CAST(Metadata_Data.IntValue AS varchar), 
                      CASE WHEN Metadata_Data.BoolValue = 1 THEN 'Yes' WHEN Metadata_Data.BoolValue = 0 THEN 'No' ELSE NULL END, CAST(Metadata_Data.DoubleValue AS varchar), CAST(Metadata_Data.DateValue AS varchar)) 
                      AS Value, Metadata_Data.DateChanged AS dtl_DateEntered, Account_User.DisplayName AS dd_UserName
FROM         ProcessDefinition_ProjectPlan INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                      Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = Metadata_Data.ForeignId INNER JOIN
                      Account_User ON Metadata_Data.ChangedByUserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
                      ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId LEFT OUTER JOIN
                      ProcessDefinition_ProjectPlanTask AS ParentTask ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ParentTask.ProjectPlanTaskId
WHERE     (Metadata_Data.ForeignType = 15) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId)
UNION
SELECT     ProcessDefinition_ProjectPlan.ProjectPlanName AS dd_ProjectPlanName, ParentTask.TaskName AS dd_ParentTaskName, 
                      ProcessDefinition_ProjectPlanTask.TaskName AS dd_TaskName, ProcessDefinition_ProcessHistory.MinorVersion AS Revision, 
                      ProcessDefinition_ProcessHistory.ProcessTitle, Metadata_MetadataField.ScreenLabel AS dd_DataLabel, COALESCE (Metadata_Data.StringValue, 
                      CAST(Metadata_Data.IntValue AS varchar), CASE WHEN Metadata_Data.BoolValue = 1 THEN 'Yes' WHEN Metadata_Data.BoolValue = 0 THEN 'No' ELSE NULL END, CAST(Metadata_Data.DoubleValue AS varchar), 
                      CAST(Metadata_Data.DateValue AS varchar)) AS Value, Metadata_Data.DateChanged AS dtl_DateEntered, Account_User.DisplayName AS dd_UserName
FROM         ProcessDefinition_ProjectPlan INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                      Account_User INNER JOIN
                      Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId ON 
                      Account_User.UserId = Metadata_Data.ChangedByUserId INNER JOIN
                      ProcessDefinition_ProjectPlanTaskLink ON Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskLink.TaskId INNER JOIN
                      ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId LEFT OUTER JOIN
                      ProcessDefinition_ProjectPlanTask AS ParentTask ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ParentTask.ProjectPlanTaskId
WHERE     (Metadata_Data.ForeignType = 14) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UpdateProfile]'
GO
CREATE PROCEDURE [dbo].[Account_UpdateProfile] 
		@userId int, 
	@Profile nvarchar(max),
	@SendNotifications bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	UPDATE Account_User 
	SET [Profile] = @Profile, SendNotifications=@SendNotifications
	WHERE UserId = @userId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetAssignedTags]'
GO
CREATE PROCEDURE [dbo].[Notes_GetAssignedTags]
		@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	IF(@foreignType=22)
	BEGIN

	   DECLARE @lastPublishedId int
	   SELECT @lastPublishedId=MAX(ProcessDefinition_Publish.PublishId)
	   FROM  ProcessDefinition_Publish INNER JOIN
			  ProcessDefinition_Repository ON ProcessDefinition_Publish.RepositoryId = ProcessDefinition_Repository.RepositoryId INNER JOIN
			  ProcessDefinition_Process ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Process.ForeignId
	   WHERE (ProcessDefinition_Process.ForeignType = 7) AND (ProcessDefinition_Process.ProcessId = @foreignId)


	    SELECT     Notes_PublishedTag.TagName, Notes_PublishedAssignedTag.AssignedTagId, TagUsage.AssignedTagCount, Notes_PublishedAssignedTag.TagId
	    FROM         Notes_PublishedAssignedTag INNER JOIN
							 Notes_PublishedTag ON Notes_PublishedAssignedTag.TagId = Notes_PublishedTag.TagId INNER JOIN
								 (SELECT     TagId, COUNT(AssignedTagId) AS AssignedTagCount
								    FROM          Notes_PublishedAssignedTag AS Notes_AssignedTag_1
								    GROUP BY TagId) AS TagUsage ON Notes_PublishedAssignedTag.TagId = TagUsage.TagId
	    WHERE     (Notes_PublishedAssignedTag.ForeignId = @foreignId) AND (Notes_PublishedAssignedTag.ForeignType = 144021)
			 AND (Notes_PublishedAssignedTag.PublishId=@lastPublishedId) AND (Notes_PublishedTag.PublishId=@lastPublishedId)
	    ORDER BY Notes_PublishedTag.TagName

	END
	ELSE
	BEGIN
	    SELECT     Notes_Tag.TagName, Notes_AssignedTag.AssignedTagId, TagUsage.AssignedTagCount, Notes_AssignedTag.TagId
	    FROM         Notes_AssignedTag INNER JOIN
							 Notes_Tag ON Notes_AssignedTag.TagId = Notes_Tag.TagId INNER JOIN
								 (SELECT     TagId, COUNT(AssignedTagId) AS AssignedTagCount
								    FROM          Notes_AssignedTag AS Notes_AssignedTag_1
								    GROUP BY TagId) AS TagUsage ON Notes_AssignedTag.TagId = TagUsage.TagId
	WHERE     (Notes_AssignedTag.ForeignId = @foreignId) AND (Notes_AssignedTag.ForeignType = @foreignType)
	    ORDER BY Notes_Tag.TagName
	END
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetTagAutocompleteListForAssignor]'
GO
CREATE PROCEDURE [dbo].[Notes_GetTagAutocompleteListForAssignor] 
	@prefix nvarchar(100),
	@AssignedByForeignId int,
	@AssignedByForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @prefixLen int
	SET @prefixLen=LEN(@prefix)

	SELECT     Notes_Tag.TagName
	FROM         Notes_Tag INNER JOIN
						  Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId
	WHERE     (Notes_AssignedTag.AssignedByForeignId = @AssignedByForeignId) AND (Notes_AssignedTag.AssignedByForeignType = @AssignedByForeignType)
	GROUP BY Notes_Tag.TagName, LEN(Notes_Tag.TagName)
	HAVING      (LEFT(Notes_Tag.TagName, @prefixLen) = @prefix)
	ORDER BY LEN(Notes_Tag.TagName), Notes_Tag.TagName
END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StepPredecessor]'
GO
CREATE TABLE [dbo].[ProcessDefinition_StepPredecessor]
(
[StepPredecessorId] [int] NOT NULL IDENTITY(1, 1),
[ParentProcessId] [int] NOT NULL,
[ProcessStepId] [int] NOT NULL,
[StepUId] [uniqueidentifier] NOT NULL,
[FromProcessStepId] [int] NOT NULL,
[FromStepUId] [uniqueidentifier] NOT NULL,
[PredecessorText] [nvarchar] (250) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_StepPredecessor] on [dbo].[ProcessDefinition_StepPredecessor]'
GO
ALTER TABLE [dbo].[ProcessDefinition_StepPredecessor] ADD CONSTRAINT [PK_ProcessDefinition_StepPredecessor] PRIMARY KEY CLUSTERED  ([StepPredecessorId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateStepPredecessor]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_CreateStepPredecessor] 
	@ParentProcessId int,
	@StepUId uniqueidentifier,
	@FromStepUId uniqueidentifier,
	@PredecessorText nvarchar(250)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		DECLARE @stepId int
	DECLARE @fromStepId int

	SELECT @stepId = ProcessStepId FROM ProcessDefinition_Step WHERE StepUId = @StepUId
	SELECT @fromStepId = ProcessStepId FROM ProcessDefinition_Step WHERE StepUId = @FromStepUId

	INSERT INTO [ProcessDefinition_StepPredecessor]
           ([ParentProcessId]
           ,[ProcessStepId]
           ,[StepUId]
           ,[FromProcessStepId]
           ,[FromStepUId]
           ,[PredecessorText])
     VALUES (@ParentProcessId, @stepId, @StepUId, @fromStepId, @FromStepUId, @PredecessorText)

	RETURN Scope_Identity()
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetAssignedAvailableTags]'
GO
CREATE PROCEDURE [dbo].[Notes_GetAssignedAvailableTags]
		@foreignId int,
	@foreignType int,
	@TagForeignId int,
	@TagForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	SELECT     Notes_Tag.TagName, Notes_Tag.TagId, AssignedTags.AssignedTagId
	FROM         (SELECT     AssignedTagId, TagId
						   FROM          Notes_AssignedTag AS Notes_AssignedTag_1
						   WHERE      (ForeignId = @foreignId) AND (ForeignType = @foreignType)) AS AssignedTags RIGHT OUTER JOIN
						  Notes_Tag ON AssignedTags.TagId = Notes_Tag.TagId
	WHERE     (Notes_Tag.ForeignId = @TagForeignId) AND (Notes_Tag.ForeignType = @TagForeignType)
	ORDER BY Notes_Tag.TagName
END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO


GO
PRINT N'Creating [dbo].[Notes_GetAllTags]'
GO
CREATE PROCEDURE [dbo].[Notes_GetAllTags]
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     TagId, TagName
	FROM         Notes_Tag
	ORDER BY TagName

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLastPublishedProcessHistory]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLastPublishedProcessHistory]
    @ProcessId int,
    @RepositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @repositoryId int
	SET @repositoryId=dbo.ProcessDefinition_GetRepositoryId(@RepositoryName)

    DECLARE @lastPublishedId int

    SELECT @lastPublishedId=MAX(PublishId)
    FROM  ProcessDefinition_Publish
    WHERE (RepositoryId = @repositoryId)

    SELECT ProcessHistoryId
    FROM  ProcessDefinition_PublishProcess
    WHERE (PublishId = @lastPublishedId) AND (ProcessId = @ProcessId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLatestReposDiscussion]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLatestReposDiscussion] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Discussion.CreatedDateTime, 
                      Account_User.DisplayName
FROM         ProcessDefinition_Process INNER JOIN
                          (SELECT     TOP (5) MAX(ProcessDefinition_Discussion_1.DiscussionId) AS LastDiscussionId, ProcessDefinition_ProcessHistory.ProcessId
                            FROM          ProcessDefinition_ProcessHistory INNER JOIN
                                                   ProcessDefinition_Discussion AS ProcessDefinition_Discussion_1 ON 
                                                   ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_Discussion_1.ForeignId
                            WHERE      (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)
                            GROUP BY ProcessDefinition_ProcessHistory.ProcessId) AS LastDiscuss ON ProcessDefinition_Process.ProcessId = LastDiscuss.ProcessId INNER JOIN
                      ProcessDefinition_Discussion ON LastDiscuss.LastDiscussionId = ProcessDefinition_Discussion.DiscussionId INNER JOIN
                      Account_User ON ProcessDefinition_Discussion.UserId = Account_User.UserId
WHERE ProcessDefinition_Process.IsDeleted = 0
ORDER BY ProcessDefinition_Discussion.CreatedDateTime DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_NotificationEvent]'
GO
CREATE TABLE [dbo].[ProcessDefinition_NotificationEvent]
(
[NotificationEventId] [int] NOT NULL IDENTITY(1, 1),
[EventId] [int] NOT NULL,
[EmailTemplateId] [int] NOT NULL,
[NotificationStart] [datetime] NOT NULL,
[NotificationEnd] [datetime] NULL,
[ProjectPlanId] [int] NULL,
[TaskId] [int] NULL,
[IsActive] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_NotificationEvent_IsActive] DEFAULT ((1))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_NotificationEvent] on [dbo].[ProcessDefinition_NotificationEvent]'
GO
ALTER TABLE [dbo].[ProcessDefinition_NotificationEvent] ADD CONSTRAINT [PK_ProcessDefinition_NotificationEvent] PRIMARY KEY CLUSTERED  ([NotificationEventId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateTaskEstimateNotifications]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateTaskEstimateNotifications] 
		@taskId int, 
	@estimatedStartDate datetime,
	@estimatedFinishDate datetime
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		
	DECLARE @oldEstStart datetime
	DECLARE @oldEstEnd	datetime
	DECLARE @projectPlanId int

	SELECT @oldEstStart = EstimatedStartDate, @oldEstEnd = EstimatedEndDate, @projectPlanId = ProjectPlanId
	FROM ProcessDefinition_ProjectPlanTask
	WHERE     (ProjectPlanTaskId = @taskId)

	
	IF( (@oldEstStart IS NULL AND NOT(@estimatedStartDate IS NULL)) OR
( NOT(@estimatedStartDate IS NULL) AND @estimatedStartDate <> @oldEstStart))
	BEGIN
		UPDATE ProcessDefinition_NotificationEvent
		SET IsActive = 0 
		WHERE EventId = 1 AND ProjectPlanId = @projectPlanId AND TaskId = @taskId

		INSERT INTO ProcessDefinition_NotificationEvent(EventId, EmailTemplateId, NotificationStart, NotificationEnd, ProjectPlanId, TaskId, IsActive)
		VALUES (1, 5, DATEADD(d, -1, @estimatedStartDate), DATEADD(d, 1, @estimatedStartDate), @projectPlanId, @taskId, 1) 
	END

	IF( (@oldEstEnd IS NULL AND NOT(@estimatedFinishDate IS NULL)) OR
 ( NOT(@estimatedFinishDate IS NULL) AND @estimatedFinishDate <> @oldEstEnd))
	BEGIN
		UPDATE ProcessDefinition_NotificationEvent
		SET IsActive = 0 
		WHERE EventId = 2 AND ProjectPlanId = @projectPlanId AND TaskId = @taskId

		INSERT INTO ProcessDefinition_NotificationEvent(EventId, EmailTemplateId, NotificationStart, NotificationEnd, ProjectPlanId, TaskId, IsActive)
		VALUES (2, 6, DATEADD(d, -1, @estimatedFinishDate), DATEADD(d, 1, @estimatedFinishDate), @projectPlanId, @taskId, 1) 
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProcessList]'
GO
CREATE PROCEDURE [dbo].[Report_ProcessList] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_Process.ProcessTitle AS tf_Process, 
				ProcessDefinition_Process.PrettyPostTitle AS tf_LinkName, 
				ProcessDefinition_Process.MinorVersion as n_Revision, 
				ProcessDefinition_Process.DateCreated as dtl_Created, 
				ProcessDefinition_Process.DateUpdated as dtl_Updated, 
				Account_User.DisplayName  AS dd_LastEditor, 
				Account_User.MemberEmailAddress AS tf_Email
	FROM         ProcessDefinition_Process INNER JOIN
						  Account_User ON ProcessDefinition_Process.UserId = Account_User.UserId
	WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId AND ProcessDefinition_Process.IsDeleted=0)
	ORDER BY ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectMember]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectMember]
(
[ProjectMemberId] [int] NOT NULL IDENTITY(1, 1),
[ProjectId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[ProjectMemberRole] [int] NOT NULL,
[ForceFilteredView] [bit] NOT NULL CONSTRAINT [DF_ProcessDefinition_ProjectMember_ForceFilteredView] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectMember] on [dbo].[ProcessDefinition_ProjectMember]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectMember] ADD CONSTRAINT [PK_ProcessDefinition_ProjectMember] PRIMARY KEY CLUSTERED  ([ProjectMemberId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectMember_ProjectId] on [dbo].[ProcessDefinition_ProjectMember]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectMember_ProjectId] ON [dbo].[ProcessDefinition_ProjectMember] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectMember_UserId] on [dbo].[ProcessDefinition_ProjectMember]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectMember_UserId] ON [dbo].[ProcessDefinition_ProjectMember] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_NotificationLog]'
GO
CREATE TABLE [dbo].[ProcessDefinition_NotificationLog]
(
[NotificationLogId] [int] NOT NULL IDENTITY(1, 1),
[NotificationEventId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[DateSent] [datetime] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_NotificationLog] on [dbo].[ProcessDefinition_NotificationLog]'
GO
ALTER TABLE [dbo].[ProcessDefinition_NotificationLog] ADD CONSTRAINT [PK_ProcessDefinition_NotificationLog] PRIMARY KEY CLUSTERED  ([NotificationLogId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetNotificationsDue]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetNotificationsDue] 
		@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_NotificationEvent.NotificationEventId, ProcessDefinition_NotificationEvent.EventId, ProcessDefinition_NotificationEvent.EmailTemplateId, 
                      ProcessDefinition_NotificationEvent.ProjectPlanId, ProcessDefinition_NotificationEvent.TaskId, Account_User.DisplayName, Account_User.MemberEmailAddress, 
                      Account_User.UserId
FROM         ProcessDefinition_NotificationEvent INNER JOIN
                          (
														SELECT     ProcessDefinition_ProjectMember.UserId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS TaskId
                            FROM          ProcessDefinition_ProjectPlan INNER JOIN
                                                   ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                                                   ProcessDefinition_ProjectMember ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_ProjectMember.ProjectId
                            WHERE      (ProcessDefinition_ProjectMember.UserId = @userId) AND (ProcessDefinition_ProjectMember.ProjectMemberRole = 3)
                           
							UNION
			
							                            SELECT     AssignedToId AS UserId, TaskId
                            FROM         ProcessDefinition_ProjectPlanTaskAssignment
                            WHERE     (AssignedToId = @userId)

							UNION

														SELECT     AssignedToId AS UserId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
							FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
												  ProcessDefinition_ProjectPlanTaskAssignment ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
							WHERE     (ProcessDefinition_ProjectPlanTask.TaskProcessId IS NULL)

) AS UserToTask ON ProcessDefinition_NotificationEvent.TaskId = UserToTask.TaskId INNER JOIN
                      Account_User ON UserToTask.UserId = Account_User.UserId
WHERE     (ProcessDefinition_NotificationEvent.NotificationStart >= GetUtcDate()) 
	AND ((ProcessDefinition_NotificationEvent.NotificationEnd IS NULL) OR (ProcessDefinition_NotificationEvent.NotificationEnd >= GetUtcDate()))
	AND  (ProcessDefinition_NotificationEvent.NotificationEventId NOT IN
                          (SELECT     NotificationEventId
                            FROM          ProcessDefinition_NotificationLog
                            WHERE      (UserId = @userId))) AND (Account_User.UserId = @userId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllNotificationsDue]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAllNotificationsDue] 
	WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_NotificationEvent.NotificationEventId, ProcessDefinition_NotificationEvent.EventId, ProcessDefinition_NotificationEvent.EmailTemplateId, 
                      ProcessDefinition_NotificationEvent.ProjectPlanId, ProcessDefinition_NotificationEvent.TaskId, Account_User.DisplayName, Account_User.MemberEmailAddress, 
                      Account_User.UserId, ProcessDefinition_Project.ProjectName, ProcessDefinition_ProjectPlanTask_1.TaskName, 
                      ProcessDefinition_ProjectPlanTask_1.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask_1.EstimatedStartDate, 
                      ProcessDefinition_ProjectPlanTask_1.EstimatedEndDate, ProcessDefinition_ProjectPlanTask_1.ActualStartDate, ProcessDefinition_ProjectPlanTask_1.ActualEndDate, 
                      ProcessDefinition_Repository.RepositoryName
FROM         ProcessDefinition_NotificationEvent INNER JOIN
                          (
														SELECT     ProcessDefinition_ProjectMember.UserId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId AS TaskId
                            FROM          ProcessDefinition_ProjectPlan INNER JOIN
                                                   ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
                                                   ProcessDefinition_ProjectMember ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_ProjectMember.ProjectId
                            WHERE      (ProcessDefinition_ProjectMember.ProjectMemberRole = 3)

                            UNION
			
							                            SELECT     AssignedToId AS UserId, TaskId
                            FROM         ProcessDefinition_ProjectPlanTaskAssignment

							UNION

														SELECT     AssignedToId AS UserId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
							FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
												  ProcessDefinition_ProjectPlanTaskAssignment ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
							WHERE     (ProcessDefinition_ProjectPlanTask.TaskProcessId IS NULL)

) AS UserToTask ON ProcessDefinition_NotificationEvent.TaskId = UserToTask.TaskId INNER JOIN
                      Account_User ON UserToTask.UserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_ProjectPlan AS ProcessDefinition_ProjectPlan_1 ON 
                      ProcessDefinition_NotificationEvent.ProjectPlanId = ProcessDefinition_ProjectPlan_1.ProjectPlanId INNER JOIN
                      ProcessDefinition_Project ON ProcessDefinition_ProjectPlan_1.ProjectId = ProcessDefinition_Project.ProjectId INNER JOIN
                      ProcessDefinition_ProjectPlanTask AS ProcessDefinition_ProjectPlanTask_1 ON 
                      ProcessDefinition_NotificationEvent.TaskId = ProcessDefinition_ProjectPlanTask_1.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_Repository ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_Repository.RepositoryId
WHERE  SendNotifications = 1 AND   (ProcessDefinition_NotificationEvent.NotificationStart <= GetUtcDate()) 
	AND ((ProcessDefinition_NotificationEvent.NotificationEnd IS NULL) OR (ProcessDefinition_NotificationEvent.NotificationEnd >= GetUtcDate()))
	AND  (ProcessDefinition_NotificationEvent.NotificationEventId NOT IN
                          (SELECT     NotificationEventId
                            FROM          ProcessDefinition_NotificationLog)) AND (ProcessDefinition_NotificationEvent.IsActive = 1)END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Audit_Audit]'
GO
CREATE TABLE [dbo].[Audit_Audit]
(
[AuditId] [int] NOT NULL IDENTITY(1, 1),
[UserName] [nvarchar] (255) NOT NULL,
[BusinessServiceName] [nvarchar] (255) NOT NULL,
[Params] [nvarchar] (max) NOT NULL,
[EventDateTime] [datetime] NOT NULL CONSTRAINT [DF_Audit_Audit_EventDateTime] DEFAULT (getutcdate()),
[IpAddress] [varchar] (16) NULL,
[Failed] [bit] NOT NULL CONSTRAINT [DF_Audit_Audit_Failed] DEFAULT ((0)),
[FailureMessage] [nvarchar] (500) NULL,
[ClassName] [nvarchar] (255) NULL,
[Duration] [int] NOT NULL CONSTRAINT [DF_Audit_Audit_Duration] DEFAULT ((-1))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Audit_Audit] on [dbo].[Audit_Audit]'
GO
ALTER TABLE [dbo].[Audit_Audit] ADD CONSTRAINT [PK_Audit_Audit] PRIMARY KEY CLUSTERED  ([AuditId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Audit_CreateEvent]'
GO


CREATE PROCEDURE [dbo].[Audit_CreateEvent] 
	@userName nvarchar(255),
	@businessServiceName nvarchar(255),
	@params nvarchar(max),
	@IpAddress nvarchar(16),
	@Failed bit, 
	@FailureText nvarchar(500),
	@Duration int,
	@ClassName nvarchar(255),
	@AuditId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	INSERT INTO Audit_Audit (UserName, BusinessServiceName, Params,IpAddress, Failed, FailureMessage, Duration, ClassName)
	VALUES     (@userName, @businessServiceName, @params, @IpAddress, @Failed, @FailureText, @Duration, @ClassName)

	SET @AuditId = SCOPE_IDENTITY()
END






GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_Email]'
GO
CREATE TABLE [dbo].[Email_Email]
(
[EmailId] [int] NOT NULL IDENTITY(1, 1),
[TemplateId] [int] NOT NULL,
[Subject] [nvarchar] (256) NOT NULL,
[Body] [nvarchar] (max) NOT NULL,
[ToAddress] [nvarchar] (512) NOT NULL,
[CcAddress] [nvarchar] (512) NOT NULL,
[FromAddress] [nvarchar] (512) NOT NULL,
[BccAddress] [nvarchar] (512) NOT NULL,
[ReadReceipt] [nvarchar] (512) NOT NULL,
[SentDt] [datetime] NULL,
[ForeignType] [int] NOT NULL,
[ForeignId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_CreateEmail]'
GO
CREATE PROCEDURE [dbo].[Email_CreateEmail]
	(
	@TemplateId int,
	@Subject nvarchar(256),
	@Body nvarchar(max),
	@ToAddress nvarchar(512),
	@CcAddress nvarchar(512),
	@FromAddress nvarchar(512),
	@BccAddress nvarchar(512),
	@ReadReceipt nvarchar(512),
	@foreignType int,
	@foreignId int,
	@EmailId int OUTPUT 
	)
WITH ENCRYPTION AS

INSERT INTO Email_Email
                      (TemplateId, Subject, Body, ToAddress, CcAddress, FromAddress, BccAddress, ReadReceipt, ForeignType, ForeignId)
VALUES     (@TemplateId, @Subject, @Body, @ToAddress, @CcAddress, @FromAddress, @BccAddress, @ReadReceipt, @foreignType, @foreignId)

SET @EmailId = SCOPE_IDENTITY()

	RETURN

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProcessType]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProcessType]
(
     @repositoryName nvarchar(256),
      @ProcessTypeName nvarchar(128),
      @ProcessTypeTemplate nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

 
     INSERT INTO ProcessDefinition_ProcessType
      (
            RepositoryId, 
            ProcessTypeName, 
            ProcessTypeTemplate

      ) VALUES (
            @RepositoryId, 
            @ProcessTypeName, 
            @ProcessTypeTemplate
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetNotificationSent]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetNotificationSent] 
		@notificationEventId int, 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	INSERT INTO ProcessDefinition_NotificationLog(NotificationEventId, UserId, DateSent)
	VALUES(@notificationEventId, @userId, GetUtcDate())

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RepositorySettings]'
GO
CREATE TABLE [dbo].[ProcessDefinition_RepositorySettings]
(
[RepositoryId] [int] NOT NULL,
[PersonProcessTypeId] [int] NULL,
[ProcessTypeId] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_RepositorySettings_RepositoryId] on [dbo].[ProcessDefinition_RepositorySettings]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_RepositorySettings_RepositoryId] ON [dbo].[ProcessDefinition_RepositorySettings] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_RepositorySettings_PersonProcessTypeId] on [dbo].[ProcessDefinition_RepositorySettings]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_RepositorySettings_PersonProcessTypeId] ON [dbo].[ProcessDefinition_RepositorySettings] ([PersonProcessTypeId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectMemberRole]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectMemberRole]
(
[ProjectMemberRoleId] [int] NOT NULL IDENTITY(1, 1),
[UserId] [int] NOT NULL,
[RoleProcessId] [int] NOT NULL,
[ProjectId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectMemberRole] on [dbo].[ProcessDefinition_ProjectMemberRole]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectMemberRole] ADD CONSTRAINT [PK_ProcessDefinition_ProjectMemberRole] PRIMARY KEY CLUSTERED  ([ProjectMemberRoleId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectMemberRole_UserId] on [dbo].[ProcessDefinition_ProjectMemberRole]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectMemberRole_UserId] ON [dbo].[ProcessDefinition_ProjectMemberRole] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectMemberRole_RoleProcessId] on [dbo].[ProcessDefinition_ProjectMemberRole]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectMemberRole_RoleProcessId] ON [dbo].[ProcessDefinition_ProjectMemberRole] ([RoleProcessId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ProjectMemberRole_ProjectId] on [dbo].[ProcessDefinition_ProjectMemberRole]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ProjectMemberRole_ProjectId] ON [dbo].[ProcessDefinition_ProjectMemberRole] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectRoles]'
GO


CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectRoles] 
		@projectId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    
	
SELECT  ProcessTitle, ProcessId, CAST(CASE WHEN MemberRoles.UserId IS NULL THEN 0 ELSE 1 END AS bit) AS HasRole, [Current]
FROM(
SELECT     ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.ProcessId, CAST('1' AS bit) AS [Current] 
FROM         ProcessDefinition_Project INNER JOIN
                      ProcessDefinition_RepositorySettings ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_RepositorySettings.RepositoryId INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_RepositorySettings.PersonProcessTypeId = ProcessDefinition_Process.ProcessTypeId  
WHERE     (ProcessDefinition_Project.ProjectId = @projectId) 
UNION 
SELECT     ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.ProcessId, CAST('0' AS bit) AS [Current]
FROM         ProcessDefinition_Project INNER JOIN
                      ProcessDefinition_RepositorySettings ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_RepositorySettings.RepositoryId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_RepositorySettings.PersonProcessTypeId = ProcessDefinition_ProcessHistory.ProcessTypeId  
WHERE     (ProcessDefinition_Project.ProjectId = @projectId) 
) AS RoleProcesses LEFT OUTER JOIN
(SELECT     ProjectMemberRoleId, UserId, RoleProcessId
					FROM         ProcessDefinition_ProjectMemberRole
					WHERE     (UserId = @userId) AND ProjectId = @projectId) AS MemberRoles ON MemberRoles.RoleProcessId = RoleProcesses.ProcessId
END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessType]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessType]
(
     @repositoryName nvarchar(256),
      @ProcessTypeId int,
      @ProcessTypeName nvarchar(128),
      @ProcessTypeTemplate nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

 
     UPDATE ProcessDefinition_ProcessType SET
            ProcessTypeTemplate=@ProcessTypeTemplate,
       ProcessTypeName=@ProcessTypeName
		WHERE  ProcessTypeId=@ProcessTypeId
		AND RepositoryId=@RepositoryId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaskAlternatives]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaskAlternatives] 
	@repositoryName nvarchar(256),
	@taskGuid nvarchar(50),
	@altGroup nvarchar(256) 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)


	SELECT     ProcessDefinition_ProcessHistory.ProcessHistoryId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.ProcessId, 
						  ProcessDefinition_ProcessHistory.DescriptionSnippet
	FROM         ProcessDefinition_ProjectProcessVersion INNER JOIN
						  ProcessDefinition_ProcessHistory ON 
						  ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId LEFT OUTER JOIN
						  ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectProcessVersion.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId
	WHERE     (ProcessDefinition_ProcessHistory.AltGroup = @altGroup) AND (ProcessDefinition_ProjectPlanTask.TaskGuid = @taskGuid) AND 
						  (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Utils_Splitstring]'
GO


CREATE FUNCTION [dbo].[Utils_Splitstring] (

    @sInputList varchar(8000)   , @Delimiter char(1) = ',' )   RETURNS @List TABLE (Item varchar(8000))

WITH ENCRYPTION AS BEGIN

DECLARE @Item Varchar(8000)
DECLARE @Pos int       , @NextPos int       , @LenInput int       , @LenNext int       , @DelimLen int 
SELECT @Pos = 1
     , @DelimLen = LEN(@Delimiter)      , @LenInput = LEN(@sInputList)
     , @NextPos = CharIndex(@Delimiter, @sInputList, 1) 

IF @Delimiter = ' ' BEGIN
   INSERT INTO @List 
       SELECT 'ERROR: Blank is not a valid delimiter'
   RETURN
END


While @Pos <= @LenInput and @NextPos > 0 BEGIN

    IF @NextPos > @Pos BEGIN        SET @LenNext = @NextPos - @Pos           
       Set @Item = LTrim(RTrim(
                            substring(@sInputList
                                   , @Pos
                                  , @LenNext)
                               )
                         ) 
       IF LEN(@Item) > 0 
           Insert Into @List Select @Item
       
    END 
        SELECT @Pos = @NextPos + @DelimLen
         , @NextPos = CharIndex(@Delimiter
                              , @sInputList
                              , @Pos) 
END

SET @Item = LTrim(RTrim(
                      SUBSTRING(@sInputList
                               , @Pos
                               , @LenInput-@Pos + 1)
                       )
                 )

IF Len(@Item) > 0    INSERT INTO @List SELECT @Item

RETURN
END












GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProjectRoles]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProjectRoles] 
		@userId int,
	@projectId int,
	@RoleProcessIds varchar(1024)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DELETE FROM ProcessDefinition_ProjectMemberRole WHERE UserId = @userId AND ProjectId = @projectId

	INSERT INTO ProcessDefinition_ProjectMemberRole 
		(UserId, RoleProcessId, ProjectId)
		SELECT @userId AS UserId, RoleProcessIds.Item AS RoleProcessIds, @projectId AS ProjectId
			FROM dbo.Utils_Splitstring(@RoleProcessIds, ',') AS RoleProcessIds
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessType]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessType]
(
     @ProcessTypeId int,
     @repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

     SELECT 
            ProcessTypeName, 
            ProcessTypeTemplate
            FROM ProcessDefinition_ProcessType WHERE ProcessTypeId=@ProcessTypeId 
				AND RepositoryId=@RepositoryId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAlternatives]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAlternatives] 
	@repositoryName nvarchar(256),
	@altGroup nvarchar(256),
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT ProcessId, ProcessTitle, PrettyPostTitle, AltGroup
	FROM ProcessDefinition_ProcessHistory
	WHERE   ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1)) AND AltGroup = @altGroup 
			AND ForeignId = @RepositoryId


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanProcesses]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanProcesses]
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN

		
	DECLARE @RepositoryId int
	SELECT     @RepositoryId=ProcessDefinition_Project.RepositoryId
	FROM         ProcessDefinition_ProjectPlan INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)
 
               SET NOCOUNT ON;



SELECT     ProcessDefinition_ProcessHistory.DateCreated, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, 
                      ProcessDefinition_ProcessHistory.DateUpdated, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.DescriptionSnippet, 
                      ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, ProcessDefinition_ProcessHistory.ProcessId, 
                      ProcessDefinition_ProcessHistory.ProcessTypeId, ISNULL(COUNT(TypeMetrics.MetadataId), 0) + ISNULL(COUNT(SpecificMetrics.MetadataId), 0) AS MetricCount
FROM         ProcessDefinition_ProjectProcessType INNER JOIN
                      ProcessDefinition_ProcessHistory INNER JOIN
                      ProcessDefinition_ProjectProcessVersion ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProjectProcessVersion.ProcessHistoryId ON 
                      ProcessDefinition_ProjectProcessType.ProcessTypeId = ProcessDefinition_ProcessHistory.ProcessTypeId LEFT OUTER JOIN
                          (SELECT     ForeignId, ForeignType, MetadataId
                            FROM          Metadata_MetadataField AS Metadata_MetadataField_1
                            WHERE      (ForeignType = 13)) AS SpecificMetrics ON ProcessDefinition_ProjectProcessVersion.ProjectProcessId = SpecificMetrics.ForeignId LEFT OUTER JOIN
                          (SELECT     ForeignId, ForeignType, MetadataId
                            FROM          Metadata_MetadataField
                            WHERE      (ForeignType = 12)) AS TypeMetrics ON ProcessDefinition_ProjectProcessType.ProjectProcessTypeId = TypeMetrics.ForeignId
WHERE     (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId) AND (ProcessDefinition_ProjectProcessType.ProjectPlanId = @projectPlanId) AND 
                      (ProcessDefinition_ProcessHistory.ForeignId = @RepositoryId)
GROUP BY ProcessDefinition_ProcessHistory.DateCreated, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.DateUpdated, 
                      ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.DescriptionSnippet, ProcessDefinition_ProcessHistory.MajorVersion, 
                      ProcessDefinition_ProcessHistory.MinorVersion, ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.ProcessTypeId, 
                      ProcessDefinition_ProcessHistory.IsPublished

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RepositoryPin]'
GO
CREATE TABLE [dbo].[ProcessDefinition_RepositoryPin]
(
[RepositoryPinId] [int] NOT NULL IDENTITY(1, 1),
[UserId] [int] NOT NULL,
[RepositoryId] [int] NOT NULL,
[ProjectId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_RepositoryPin] on [dbo].[ProcessDefinition_RepositoryPin]'
GO
ALTER TABLE [dbo].[ProcessDefinition_RepositoryPin] ADD CONSTRAINT [PK_ProcessDefinition_RepositoryPin] PRIMARY KEY CLUSTERED  ([RepositoryPinId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_RepositoryPin_UserId] on [dbo].[ProcessDefinition_RepositoryPin]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_RepositoryPin_UserId] ON [dbo].[ProcessDefinition_RepositoryPin] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetRepositoryPin]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetRepositoryPin] 
	@userId int,
	@repositoryName nvarchar(256),
	@projectId int,
	@pinSet bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)



	DECLARE @curId int
	SELECT @curId=RepositoryPinId
	FROM  ProcessDefinition_RepositoryPin
	WHERE (RepositoryId = @RepositoryId) AND (ProjectId = @projectId) AND (UserId = @userId)

	IF(@pinSet=1 AND @curId IS NULL)
	BEGIN 
		INSERT INTO ProcessDefinition_RepositoryPin
				 (UserId, RepositoryId, ProjectId)
		VALUES (@userId,@RepositoryId,@projectId)			
	END
	ELSE
	IF(@pinSet=0 AND @curId IS NOT NULL)
	BEGIN 
		DELETE FROM ProcessDefinition_RepositoryPin
				WHERE RepositoryPinId=@curId	
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessTypes]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessTypes]
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     ProcessTypeId, ProcessTypeName, ProcessTypeTemplate, TypeUId
FROM         ProcessDefinition_ProcessType
WHERE     (RepositoryId = @RepositoryId) AND IsDeleted=0
ORDER BY ProcessTypeName
 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetMemberIdFromUserId]'
GO
CREATE PROCEDURE [dbo].[Account_GetMemberIdFromUserId] 
	@userId int, 
	@memberId UniqueIdentifier OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     @memberId=MemberId
	FROM         Account_User
	WHERE     (UserId = @userId)

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteProcessType]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteProcessType]
(
     @repositoryName nvarchar(256),
      @ProcessTypeId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

 	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	UPDATE ProcessDefinition_ProcessType 
	SET IsDeleted = 1	
	WHERE ProcessTypeId=@ProcessTypeId AND RepositoryId=@RepositoryId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUserFromMemberId]'
GO
CREATE PROCEDURE [dbo].[Account_GetUserFromMemberId]
	@memberId uniqueidentifier
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     UserId, UserType, DisplayName
	FROM         Account_User
	WHERE     (MemberId = @memberId)

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ApiSession]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ApiSession]
(
[SessionId] [int] NOT NULL IDENTITY(1, 1),
[SessionToken] [varchar] (50) NOT NULL,
[UserId] [int] NOT NULL,
[LoginTime] [datetime] NOT NULL,
[LogoutTime] [datetime] NULL,
[ExpiryTime] [datetime] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ApiSession] on [dbo].[ProcessDefinition_ApiSession]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ApiSession] ADD CONSTRAINT [PK_ProcessDefinition_ApiSession] PRIMARY KEY CLUSTERED  ([SessionId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ApiCreateSession]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ApiCreateSession]
		@sessionToken varchar(50), 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	INSERT INTO ProcessDefinition_ApiSession(SessionToken, UserId, LoginTime, ExpiryTime)
	VALUES(@sessionToken, @userId, GetUtcDate(), DATEADD(mi, 20, GetUtcDate()))

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkedProcessesForProjectPlan]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkedProcessesForProjectPlan] 
	@projectPlanTaskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;



SELECT     ProcessDefinition_ProcessLinkHistory.ProcessId, ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinkUri, 
                      ProcessDefinition_ProcessLinkHistory.FullLinkUri, ProcessDefinition_ProcessLinkHistory.LinkText, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
                      ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.ProcessTypeId, ProcessDefinition_ProcessLinkHistory.LinksToProcessId
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlanTaskLink ON ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskLink.TaskId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @projectPlanTaskId)
ORDER BY ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UpdateMemberEmail]'
GO
CREATE PROCEDURE [dbo].[Account_UpdateMemberEmail] 
	@memberId uniqueidentifier,
	@email nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE    Account_User
	SET              MemberEmailAddress = @email
	WHERE     (MemberId = @memberId)

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ApiExpireSession]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ApiExpireSession]
		@sessionToken varchar(50)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_ApiSession
	SET ExpiryTime = GetUtcDate(), LogoutTime=GetUtcDate()
	WHERE SessionToken = @sessionToken

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetPreviousVersions]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetPreviousVersions] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, 
						  ProcessDefinition_ProcessHistory.DescriptionSnippet, COALESCE (ProcessDefinition_ProcessHistory.DateUpdated, ProcessDefinition_ProcessHistory.DateCreated) 
						  AS DateUpdated, ProcessDefinition_ProcessHistory.ProcessHistoryId, 0 AS IsCurrentVersion, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
						  ProcessDefinition_ProcessHistory.DateFrozen, Account_User.DisplayName, COUNT(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId) 
						  AS UsedByTaskCount
	FROM         ProcessDefinition_ProcessHistory INNER JOIN
						  Account_User ON ProcessDefinition_ProcessHistory.UserId = Account_User.UserId LEFT OUTER JOIN
						  ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProjectPlanTask.ProcessHistoryId
	WHERE     (ProcessDefinition_ProcessHistory.ProcessId = @processId)
	GROUP BY ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.MajorVersion, ProcessDefinition_ProcessHistory.MinorVersion, 
						  ProcessDefinition_ProcessHistory.DescriptionSnippet, COALESCE (ProcessDefinition_ProcessHistory.DateUpdated, ProcessDefinition_ProcessHistory.DateCreated), 
						  ProcessDefinition_ProcessHistory.ProcessHistoryId, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.DateFrozen, 
						  Account_User.DisplayName
	ORDER BY ProcessDefinition_ProcessHistory.MinorVersion DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUserIdFromEmail]'
GO
CREATE PROCEDURE [dbo].[Account_GetUserIdFromEmail] 
		@Email varchar(128),
	@userId int OUTPUT
WITH ENCRYPTION AS
BEGIN
	SET NOCOUNT ON;

	SELECT @userId = UserId FROM Account_User WHERE UPPER(MemberEmailAddress) = UPPER(@Email)
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ApiGetSession]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ApiGetSession]
		@sessionToken varchar(50)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_ApiSession
	SET ExpiryTime = DATEADD(mi, 20, GetUtcDate())
	WHERE SessionToken = @sessionToken AND LogoutTime IS NULL AND ExpiryTime > GetUtcDate()

	SELECT UserId, ExpiryTime
	FROM ProcessDefinition_ApiSession
	WHERE SessionToken = @sessionToken AND ExpiryTime > GetUtcDate()

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanByName]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanByName] 
	@repositoryName nvarchar(256),
	@projectId int,
	@projectPlanName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     ProcessDefinition_ProjectPlan.ProjectPlanId
FROM         ProcessDefinition_ProjectPlan INNER JOIN
                      ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
WHERE     (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND (ProcessDefinition_Project.ProjectId = @projectId) AND 
                      (ProcessDefinition_ProjectPlan.ProjectPlanName  LIKE @projectPlanName)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetPreviousVersion]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetPreviousVersion]
	@processId int,
	@minorVersion int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.DescriptionSnippet, COALESCE (ProcessDefinition_ProcessHistory.DateUpdated, 
                      ProcessDefinition_ProcessHistory.DateCreated) AS DateUpdated, ProcessDefinition_ProcessHistory.ProcessHistoryId, 
                      ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, 
                      ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.IsPublished, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
                      Account_User.DisplayName, (SELECT MAX(MinorVersion) FROM ProcessDefinition_ProcessHistory WHERE (ProcessId = @processId)) AS MaxMinor
FROM         ProcessDefinition_ProcessHistory INNER JOIN
                      Account_User ON ProcessDefinition_ProcessHistory.UserId = Account_User.UserId
	WHERE     (ProcessId = @processId) AND (MinorVersion = @minorVersion)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUser]'
GO


CREATE PROCEDURE [dbo].[Account_GetUser] 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	SELECT     MemberId, UserType, CAST('' AS varchar) AS PrimaryUserTypeName, DisplayName, MemberEmailAddress, [Profile], SendNotifications
	FROM         Account_User
	WHERE     (UserId = @userId)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_HasProjectAccess]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_HasProjectAccess] 
(
	@projectId int,
	@userId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN
		DECLARE @Result bit
	SET @Result=0

	DECLARE @ProjectMemberId int
	SELECT     @ProjectMemberId=ProjectMemberId
	FROM         ProcessDefinition_ProjectMember
	WHERE     (ProjectId = @projectId) AND (UserId = @userId)

	IF(@ProjectMemberId IS NOT NULL)
	BEGIN
				SET @Result=1
	END
	ELSE
	BEGIN
		DECLARE @MemberRole int
		SELECT     @MemberRole=ProcessDefinition_Member.MemberRole
		FROM         ProcessDefinition_Member INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Project.RepositoryId
		WHERE     (ProcessDefinition_Project.ProjectId = @projectId) AND (ProcessDefinition_Member.UserId = @userId)

		IF(@MemberRole>=3)
		BEGIN
						SET @Result=1
		END

	END

		RETURN @Result

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanTaskSectionMetrics]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanTaskSectionMetrics] 
	@userId int,
	@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @projectId int
	SELECT     @projectId=ProcessDefinition_ProjectPlan.ProjectId
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	IF(dbo.ProcessDefinition_HasProjectAccess(@projectId,@userId)=1)
	BEGIN

DECLARE @RepositoryId int
	SELECT     @RepositoryId=ProcessDefinition_Project.RepositoryId
	FROM         ProcessDefinition_ProjectPlan INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectId = @projectId)
 





SELECT     ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProcessLinkHistory.LinkText, 
                      ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId AS LinksToSFid, ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId AS LinksToTFid, 
                      ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId
FROM         ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanTaskLink.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId) AND (NOT (ProcessDefinition_ProcessLinkHistory.LinksToProcessId IS NULL))
AND ( 
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField  WHERE (ForeignType = 16 AND ForeignId=ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId))
OR
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField WHERE (ForeignType = 18 AND ForeignId=ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId)))



	END


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryProcesses]
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.DateCreated, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.IsPublished, ProcessDefinition_Process.DateUpdated, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.DescriptionSnippet, ProcessDefinition_Process.MajorVersion, 
						  ProcessDefinition_Process.MinorVersion, ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.ProcessTypeId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)
	ORDER BY ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UpdateDisplayName]'
GO
CREATE PROCEDURE [dbo].[Account_UpdateDisplayName] 
	@userId int,
	@displayName nvarchar(100)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE    Account_User
	SET              DisplayName = @displayName
	WHERE     (UserId = @userId)

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_CreateUser]'
GO
CREATE PROCEDURE [dbo].[Account_CreateUser] 
		@memberId uniqueidentifier,
	@userType int,
	@displayName nvarchar(100),
	@email nvarchar(256),
	@userId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @DefaultLicense int
	SELECT @DefaultLicense = LicenseId FROM ProcessDefinition_License WHERE IsDefault=1
	IF(@DefaultLicense IS NULL)
		SET @DefaultLicense = -1	

	INSERT INTO Account_User
						  (MemberId, UserType, DisplayName, MemberEmailAddress, LicenseId)
	VALUES     (@memberId,@userType,@displayName,@email, @DefaultLicense)

	SET @userId=Scope_Identity()


END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUserByDisplayName]'
GO
CREATE PROCEDURE [dbo].[Account_GetUserByDisplayName] 
		@DisplayName nvarchar(100)
WITH ENCRYPTION AS
BEGIN
	SET NOCOUNT ON;

SELECT     UserId, UserType, DisplayName
FROM         Account_User
WHERE     (DisplayName = @DisplayName) AND (IsDeleted = 0)

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUsers]'
GO
CREATE PROCEDURE [dbo].[Account_GetUsers] 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Account_UserType.PrimaryUserTypeName, Account_User.UserId, Account_User.DisplayName, CASE WHEN Account_User.MemberId IS NULL 
						  THEN 0 ELSE 1 END AS HasAccount
	FROM         Account_User INNER JOIN
						  Account_UserType ON Account_User.UserType = Account_UserType.PrimaryUserTypeId
	ORDER BY Account_User.DisplayName

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AddProcessAccess]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_AddProcessAccess]
(
     @userId int,
      @processId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO ProcessDefinition_Access
      (
            UserId, 
            DateAccessed, 
            ProcessId

      ) VALUES (
            @userId, 
            GetUtcDate(), 
            @processId
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UpdateUser]'
GO
CREATE PROCEDURE [dbo].[Account_UpdateUser] 
	@userId int, 
	@displayName nvarchar(100)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE    Account_User
	SET              DisplayName = @displayName
	WHERE     (UserId = @userId)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProject]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProject]
(
     @repositoryName nvarchar(256),
      @ProjectName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

 
     INSERT INTO ProcessDefinition_Project
      (
            RepositoryId, 
            ProjectName

      ) VALUES (
            @RepositoryId, 
            @ProjectName
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLicense] 
		@validationCode nvarchar(50) 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     LicenseId, Info, Feature, Count, ValidFrom, ValidTo, Validation, ValidationCode
	FROM         ProcessDefinition_License
	WHERE     (ValidationCode = @validationCode)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanTaskMetrics]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanTaskMetrics] 
	@userId int,
	@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @projectId int
	SELECT     @projectId=ProcessDefinition_ProjectPlan.ProjectId
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	IF(dbo.ProcessDefinition_HasProjectAccess(@projectId,@userId)=1)
	BEGIN
		

SELECT     ProcessHistoryId AS LinksToSFid, ProcessHistoryId AS LinksToTFid
FROM         ProcessDefinition_ProjectPlanTask
WHERE     (ProjectPlanTaskId = @taskId) AND (
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField  WHERE (ForeignType = 16 AND ForeignId=ProcessDefinition_ProjectPlanTask.ProcessHistoryId))
OR
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField WHERE (ForeignType = 18 AND ForeignId=ProcessDefinition_ProjectPlanTask.ProcessHistoryId)))


	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProject]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProject]
(
     @repositoryName nvarchar(256),
     @projectId int,
      @ProjectName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

     UPDATE ProcessDefinition_Project SET
            ProjectName=@ProjectName
       WHERE ProjectId=@projectId AND RepositoryId=@RepositoryId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryGrowth]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryGrowth]
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @dtNow DateTime
	SET @dtNow=GetUtcDate()
	SELECT     COUNT(ProcessDefinition_Process.ProcessId) AS ProcessCount, 
			CASE WHEN DATEDIFF(month, ProcessDefinition_Process.DateCreated, @dtNow) >= 12 THEN 13 ELSE DATEDIFF(month, ProcessDefinition_Process.DateCreated, @dtNow) END AS CreationMonth
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted = 0
	GROUP BY CASE WHEN DATEDIFF(month, ProcessDefinition_Process.DateCreated, @dtNow) >= 12 THEN 13 ELSE DATEDIFF(month, ProcessDefinition_Process.DateCreated, @dtNow) END
	ORDER BY CreationMonth DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateLicense]'
GO
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateLicense]
(
     @Info nvarchar(256),
      @Feature nvarchar(5),
      @Count int,
      @ValidTo datetime,
      @Validation nvarchar(512),
      @ValidationCode nvarchar(50)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO ProcessDefinition_License
      (
            Info, 
            Feature, 
            [Count], 
            ValidFrom, 
            ValidTo, 
            Validation, 
            ValidationCode
      ) VALUES (
            @Info, 
            @Feature, 
            @Count, 
            GetUtcDate(), 
            @ValidTo, 
            @Validation, 
            @ValidationCode
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaskPositions]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_GetTaskPositions] 
(	
		@ParentTaskId int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(

	SELECT  TOP 100 PERCENT   ProjectPlanTaskId, ParentTaskId, TaskPosition, TaskConcurrent, CurrentStatus, ROW_NUMBER() OVER(ORDER BY TaskPosition) - 1 AS Position
	FROM         ProcessDefinition_ProjectPlanTask
	WHERE     (ParentTaskId = @ParentTaskId) AND TaskIsRemoved = 0
	ORDER BY TaskPosition

)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinitoin_GetTaskGroupIds]'
GO
CREATE FUNCTION [dbo].[ProcessDefinitoin_GetTaskGroupIds] 
(	
		@ParentTaskId int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(
	WITH TaskGroups(TaskId, ParentTaskId, Position, IsConcurrent, CurrentStatus, GroupId)
	AS
	(
		SELECT     ProjectPlanTaskId, ParentTaskId, Position, TaskConcurrent, CurrentStatus, 0
	FROM         dbo.ProcessDefinition_GetTaskPositions(@ParentTaskId)
	WHERE     (ParentTaskId = @ParentTaskId) AND Position = 0

	UNION ALL

		SELECT     ParentTasks.ProjectPlanTaskId, ParentTasks.ParentTaskId, ParentTasks.Position, 
						  ParentTasks.TaskConcurrent, ParentTasks.CurrentStatus, 
						  CASE ParentTasks.TaskConcurrent WHEN 1 THEN tg.GroupId ELSE tg.GroupId + 1 END
	FROM         dbo.ProcessDefinition_GetTaskPositions(@ParentTaskId) AS ParentTasks INNER JOIN
						  TaskGroups AS tg ON ParentTasks.ParentTaskId = tg.ParentTaskId 
	WHERE     (ParentTasks.Position = tg.Position + 1)
	)

	SELECT * FROM TaskGroups

)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CanTaskStart]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_CanTaskStart] 
(
		@TaskId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN
		DECLARE @ParentTaskId int
	DECLARE @ThisTaskGroupId int

	SELECT @ParentTaskId = ParentTaskId
	FROM ProcessDefinition_ProjectPlanTask
	WHERE ProjectPlanTaskId = @TaskId

	SELECT @ThisTaskGroupId=GroupId 
	FROM dbo.ProcessDefinitoin_GetTaskGroupIds(@ParentTaskId)
	WHERE TaskId = @TaskId	

	DECLARE @CanStart bit
	IF(@ThisTaskGroupId = 0)
	BEGIN
		IF(@ParentTaskId IS NULL)
			SET @CanStart = 1 		ELSE
		BEGIN
						SELECT @CanStart = CASE CurrentStatus WHEN 1 THEN 0 ELSE 1 END
			FROM ProcessDefinition_ProjectPlanTask
			WHERE ProjectPlanTaskId = @ParentTaskId
			
					END
	END
	ELSE
	BEGIN
		SELECT    @CanStart = CASE WHEN
								  (SELECT     COUNT(TaskId)
									FROM          dbo.ProcessDefinitoin_GetTaskGroupIds(ProcessDefinition_ProjectPlanTask.ParentTaskId)
									WHERE      GroupId = @ThisTaskGroupId - 1 AND CurrentStatus < 3) > 0 THEN 0 ELSE 1 END 
		FROM         ProcessDefinition_ProjectPlanTask 
		WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @TaskId)
	END

	
		RETURN @CanStart

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateTaskNotifications]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateTaskNotifications] 
		@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

			DECLARE @parentTaskId int
	SELECT @parentTaskId = ParentTaskId 
	FROM dbo.ProcessDefinition_ProjectPlanTask
	WHERE ProjectPlanTaskId = @taskId

	DECLARE @CanStart TABLE 
	( 
		ProjectPlanTaskId int,
		EstimatedStartDate datetime,
		ProjectPlanId int,
		CurrentStatus int,
		TaskIsRemoved  bit,
		CanStart	bit	
	)
	INSERT INTO @CanStart
	SELECT ProjectPlanTaskId, EstimatedStartDate, ProjectPlanId, CurrentStatus, TaskIsRemoved, dbo.ProcessDefinition_CanTaskStart(ProjectPlanTaskId) AS CanStart
	FROM dbo.ProcessDefinition_ProjectPlanTask
	WHERE ParentTaskId = @taskId OR ParentTaskId = @parentTaskId

	
		UPDATE ProcessDefinition_NotificationEvent
	SET IsActive = 0 
	WHERE EventId = 3 AND TaskId IN (SELECT ProjectPlanTaskId FROM @CanStart WHERE TaskIsRemoved = 1 OR CanStart = 0 OR CurrentStatus > 1) 

		INSERT INTO ProcessDefinition_NotificationEvent(EventId, EmailTemplateId, NotificationStart, NotificationEnd, ProjectPlanId, TaskId, IsActive)
	SELECT 3, 11, GetUtcDate(), NULL, ProjectPlanId, ProjectPlanTaskId, 1
	FROM @CanStart 
	WHERE TaskIsRemoved = 0 AND CanStart = 1 AND CurrentStatus = 1 AND 
		ProjectPlanTaskId NOT IN (
			SELECT TaskId 
			FROM ProcessDefinition_NotificationEvent
			WHERE EventId = 3 AND IsActive = 1)




END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProjectPlanTask]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProjectPlanTask]
(
	@TaskGuid nvarchar(256),
	@projectPlanId int,
	@TaskName nvarchar(256),
	@TaskNotes nvarchar(max),
	@TaskPosition int,
	@TaskIsRemoved bit,
	@TaskConcurrent bit,
	@RemovalReason nvarchar(max),
	@userId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @TaskId int
	SELECT @TaskId = ProjectPlanTaskId
	FROM  ProcessDefinition_ProjectPlanTask
	WHERE (TaskGuid = @TaskGuid) AND (ProjectPlanId = @projectPlanId) 

	UPDATE    ProcessDefinition_ProjectPlanTask
	SET              TaskName = @TaskName, TaskConcurrent = @TaskConcurrent, TaskIsRemoved = @TaskIsRemoved, TaskNotes = ISNULL(@TaskNotes, ''), 
						  TaskPosition = @TaskPosition, RemovalReason = @RemovalReason, EditorUserId =@userId, DateUpdated=GetUtcDate()
	WHERE     (TaskGuid = @TaskGuid) AND (ProjectPlanId = @projectPlanId) 

		EXEC dbo.ProcessDefinition_UpdateTaskNotifications @TaskId

 END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ProjectPlanTaskLinkHistory]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ProjectPlanTaskLinkHistory]
(
[TaskLinkHistoryId] [int] NOT NULL IDENTITY(1, 1),
[ProjectPlanTaskLinkId] [int] NOT NULL,
[TaskUpgradeId] [int] NOT NULL,
[LinksToProcessHistoryId] [int] NOT NULL,
[LinksToProcessId] [int] NOT NULL,
[ProcessLinkHistoryId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ProjectPlanTaskLinkHistory] on [dbo].[ProcessDefinition_ProjectPlanTaskLinkHistory]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ProjectPlanTaskLinkHistory] ADD CONSTRAINT [PK_ProcessDefinition_ProjectPlanTaskLinkHistory] PRIMARY KEY CLUSTERED  ([TaskLinkHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_HasProjectPlanAccess]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_HasProjectPlanAccess] 
(
	@projectPlanId int,
	@userId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN
		DECLARE @Result bit
	SET @Result=0

	DECLARE @ProjectMemberId int	
	SELECT @ProjectMemberId=ProcessDefinition_ProjectMember.ProjectMemberId
	FROM         ProcessDefinition_ProjectMember INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectMember.ProjectId = ProcessDefinition_ProjectPlan.ProjectId
	WHERE     (ProcessDefinition_ProjectMember.UserId = @userId) AND (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)

	IF(@ProjectMemberId IS NOT NULL)
	BEGIN
				SET @Result=1
	END
	ELSE
	BEGIN
		DECLARE @MemberRole int
		SELECT     @MemberRole=ProcessDefinition_Member.MemberRole
		FROM         ProcessDefinition_Member INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Project.RepositoryId INNER JOIN
							  ProcessDefinition_ProjectPlan ON ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectPlan.ProjectId
		WHERE     (ProcessDefinition_Member.UserId = @userId) AND (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)

		IF(@MemberRole>=3)
		BEGIN
						SET @Result=1
		END

	END

		RETURN @Result

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_DataHistoryChangeset]'
GO
CREATE TABLE [dbo].[Metadata_DataHistoryChangeset]
(
[MetadataDataHistoryChangesetId] [int] NOT NULL IDENTITY(1, 1),
[ChangesetDateTime] [datetime] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Metadata_DataHistoryChangeset] on [dbo].[Metadata_DataHistoryChangeset]'
GO
ALTER TABLE [dbo].[Metadata_DataHistoryChangeset] ADD CONSTRAINT [PK_Metadata_DataHistoryChangeset] PRIMARY KEY CLUSTERED  ([MetadataDataHistoryChangesetId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_DataHistory]'
GO
CREATE TABLE [dbo].[Metadata_DataHistory]
(
[MetadataDataHistoryId] [int] NOT NULL IDENTITY(1, 1),
[MetadataDataHistoryChangesetId] [int] NOT NULL,
[MetadataDataId] [int] NOT NULL,
[MetadataId] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL,
[StringValue] [nvarchar] (max) NULL,
[IntValue] [int] NULL,
[BoolValue] [bit] NULL,
[DoubleValue] [float] NULL,
[DateValue] [datetime] NULL,
[DateChanged] [datetime] NULL,
[ChangedByUserId] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Metadata_DataHistory] on [dbo].[Metadata_DataHistory]'
GO
ALTER TABLE [dbo].[Metadata_DataHistory] ADD CONSTRAINT [PK_Metadata_DataHistory] PRIMARY KEY CLUSTERED  ([MetadataDataHistoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_DataHistory_MetadataDataHistoryChangesetId] on [dbo].[Metadata_DataHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_DataHistory_MetadataDataHistoryChangesetId] ON [dbo].[Metadata_DataHistory] ([MetadataDataHistoryChangesetId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_DataHistory_MetadataDataId] on [dbo].[Metadata_DataHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_DataHistory_MetadataDataId] ON [dbo].[Metadata_DataHistory] ([MetadataDataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_DataHistory_MetadataId] on [dbo].[Metadata_DataHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_DataHistory_MetadataId] ON [dbo].[Metadata_DataHistory] ([MetadataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_DataHistory_ForeignId] on [dbo].[Metadata_DataHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_DataHistory_ForeignId] ON [dbo].[Metadata_DataHistory] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Metadata_DataHistory_ForeignType] on [dbo].[Metadata_DataHistory]'
GO
CREATE NONCLUSTERED INDEX [IX_Metadata_DataHistory_ForeignType] ON [dbo].[Metadata_DataHistory] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteProject]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteProject] 
	@repositoryName varchar(256), 
	@projectId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

		DECLARE @projectPlanId int
	SELECT     @projectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	FROM         ProcessDefinition_ProjectPlan INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectId) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId)	

		IF(dbo.ProcessDefinition_HasProjectPlanAccess(@projectPlanId, @userId) = 1)
	BEGIN

	delete from Metadata_DataHistory
	where ForeignType = 14 and ForeignId in (
		select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)) 

	delete from Metadata_DataHistory
	where ForeignType = 15 and ForeignId in (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from Metadata_DataHistoryChangeset
	where MetadataDataHistoryChangesetId  not in (
		select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

	delete from Metadata_DataHistoryChangeset
	where MetadataDataHistoryChangesetId  not in (
		select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

	delete from Metadata_Data
	where ForeignType = 14 and ForeignId in (
		select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)) 

	delete from Metadata_Data
	where ForeignType = 15 and ForeignId in (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from ProcessDefinition_NotificationEvent
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)


	delete from ProcessDefinition_NotificationLog
	where NotificationEventId NOT IN (SELECT NotificationEventId FROM ProcessDefinition_NotificationEvent)

	delete from ProcessDefinition_ProjectPlanRoleAssignment
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from ProcessDefinition_ProjectPlanTaskAssignment
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from ProcessDefinition_ProjectPlanTaskEvent
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from ProcessDefinition_ProjectPlanTaskLinkHistory
	where ProjectPlanTaskLinkId in ( 
		select ProjectPlanTaskLinkId from ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId))

	delete from ProcessDefinition_ProjectPlanTaskLink
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from  ProcessDefinition_ProjectPlanTaskUpgrade
	where TaskId IN (
			select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId = @projectPlanId)

	delete from  ProcessDefinition_ProjectProcessType
	where ProjectPlanId = @projectPlanId

	delete from  ProcessDefinition_ProjectProcessVersion
	where ProjectPlanId = @projectPlanId

	delete from ProcessDefinition_ProjectPlanTask 
	where ProjectPlanId = @projectPlanId

	delete from ProcessDefinition_ProjectPlan
	where ProjectPlanId = @projectPlanId


	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryActiveUsers]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryActiveUsers]
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @activeUsers int, @dtLastMonth datetime
	SET @dtLastMonth=DateAdd(month,-1,GetUtcDate())


	SELECT     @activeUsers=COUNT(DISTINCT ProcessDefinition_Access.UserId)
	FROM         ProcessDefinition_Access INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_Access.ProcessId = ProcessDefinition_Process.ProcessId INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Access.DateAccessed > @dtLastMonth) AND (ProcessDefinition_Repository.RepositoryName = @repositoryName)


	DECLARE @totalUsers int
	SELECT     @totalUsers=COUNT(DISTINCT ProcessDefinition_Member.UserId)
	FROM         ProcessDefinition_Member INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)

	SELECT @activeUsers AS ActiveUsers,@totalUsers AS TotalUsers

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLicenses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLicenses]
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     SELECT LicenseId,
			Info, 
            Feature, 
            [Count], 
            ValidFrom, 
            ValidTo, 
            Validation, 
            ValidationCode,
			IsDefault
            FROM ProcessDefinition_License

 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProject]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProject]
(
     @repositoryName nvarchar(256),
	
     @projectId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

 	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

     SELECT RepositoryId, 
            ProjectName
            FROM ProcessDefinition_Project WHERE ProjectId=@projectId AND RepositoryId=@RepositoryId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryProcessesCounts]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryProcessesCounts]
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @processThisWeek int, @totalProcesses int
	SELECT  @processThisWeek=COUNT(ProcessDefinition_Process.ProcessId)
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND (ProcessDefinition_Process.DateCreated > DATEADD(week, -1, GETUTCDATE()))

	SELECT  @totalProcesses=COUNT(ProcessDefinition_Process.ProcessId)
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)

	SELECT @processThisWeek AS ProcessesThisWeek,@totalProcesses AS TotalProcesses

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjects]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjects]
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

 
     SELECT ProjectId,
			RepositoryId, 
            ProjectName
            FROM ProcessDefinition_Project
		WHERE @RepositoryId=RepositoryId
		ORDER BY ProjectName
 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryLatestProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryLatestProcesses]
	@repositoryName nvarchar(256),
	@maxReturn int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     TOP (@maxReturn) ProcessDefinition_Process.ProcessId AS ProcessCount, COALESCE (ProcessDefinition_Process.DateUpdated, 
						  ProcessDefinition_Process.DateCreated) AS DateChanged, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, 
						  ProcessDefinition_Process.DescriptionSnippet
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted=0
	ORDER BY DateChanged DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_EmailTemplate]'
GO
CREATE TABLE [dbo].[Email_EmailTemplate]
(
[EmailTemplateId] [int] NOT NULL,
[TemplateName] [nvarchar] (255) NOT NULL,
[EmailSubject] [nvarchar] (255) NOT NULL,
[EmailBody] [nvarchar] (max) NOT NULL,
[SubstitutionsAvailable] [nvarchar] (512) NOT NULL,
[ToAddress] [nvarchar] (512) NOT NULL,
[CcAddress] [nvarchar] (512) NOT NULL,
[FromAddress] [nvarchar] (512) NOT NULL,
[BccAddress] [nvarchar] (512) NOT NULL CONSTRAINT [DF_Email_EmailTemplate_BccAddress] DEFAULT (''),
[ReadReceipt] [nvarchar] (512) NOT NULL CONSTRAINT [DF_Email_EmailTemplate_ReadReceipt] DEFAULT ('')
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Email_EmailTemplate] on [dbo].[Email_EmailTemplate]'
GO
ALTER TABLE [dbo].[Email_EmailTemplate] ADD CONSTRAINT [PK_Email_EmailTemplate] PRIMARY KEY CLUSTERED  ([EmailTemplateId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_GetEmailTemplate]'
GO

 
 
CREATE PROCEDURE [dbo].[Email_GetEmailTemplate]
(
	@EmailTemplateId int
)
WITH ENCRYPTION AS
BEGIN
 
			SET NOCOUNT ON;
 
	SELECT TemplateName, 
		EmailSubject, 
		EmailBody, 
		SubstitutionsAvailable, 
		ToAddress, 
		CcAddress, 
		FromAddress,
		BccAddress,
		ReadReceipt
		FROM Email_EmailTemplate WHERE EmailTemplateId=@EmailTemplateId
END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllUserProjects]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAllUserProjects] 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT UserRepos.ProjectId, UserRepos.ProjectName, UserRepos.RepositoryId, 
                      UserRepos.RepositoryName, UserRepos.MemberRole, UserRepos.ProjectMemberRole,
					CASE WHEN UserPins.RepositoryPinId IS NULL THEN 0 ELSE 1 END AS IsPinned
	FROM
	(

SELECT     ProcessDefinition_Project.ProjectId, ProcessDefinition_Project.ProjectName, ProcessDefinition_Repository.RepositoryId, 
                      ProcessDefinition_Repository.RepositoryName, ProcessDefinition_Member.MemberRole, 3 AS ProjectMemberRole
FROM         ProcessDefinition_Project INNER JOIN
                      ProcessDefinition_Member ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_Member.RepositoryId INNER JOIN
                      ProcessDefinition_Repository ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_Repository.RepositoryId
WHERE     (ProcessDefinition_Member.MemberRole >= 3) AND (ProcessDefinition_Member.UserId = @userId)
	UNION

	SELECT     ProcessDefinition_Project.ProjectId, ProcessDefinition_Project.ProjectName, ProcessDefinition_Repository.RepositoryId, 
						  ProcessDefinition_Repository.RepositoryName, ProcessDefinition_Member.MemberRole, ProcessDefinition_ProjectMember.ProjectMemberRole
	FROM         ProcessDefinition_Project INNER JOIN
						  ProcessDefinition_Member ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_Member.RepositoryId INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_Repository.RepositoryId INNER JOIN
						  ProcessDefinition_ProjectMember ON ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectMember.ProjectId
	WHERE     (ProcessDefinition_Member.MemberRole > 0) AND (ProcessDefinition_Member.MemberRole < 3) AND (ProcessDefinition_Member.UserId = @userId) AND 
						  (ProcessDefinition_ProjectMember.UserId = @userId)	UNION 
SELECT     NULL AS ProjectId,NULL AS ProjectName,ProcessDefinition_Repository.RepositoryId, ProcessDefinition_Repository.RepositoryName, ProcessDefinition_Member.MemberRole,
			NULL AS ProjectMemberRole
FROM         ProcessDefinition_Repository INNER JOIN
                      ProcessDefinition_Member ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Member.RepositoryId
WHERE     (ProcessDefinition_Member.UserId = @userId) AND (ProcessDefinition_Member.MemberRole > 0)
) AS UserRepos LEFT OUTER JOIN
(
SELECT RepositoryPinId,RepositoryId,ProjectId FROM
         ProcessDefinition_RepositoryPin 
		 WHERE UserId=@userId
) AS UserPins ON ISNULL(UserRepos.ProjectId,0) = UserPins.ProjectId AND UserRepos.RepositoryId = UserPins.RepositoryId
	ORDER BY IsPinned DESC,RepositoryName,ProjectName



END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryMruProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryMruProcesses]
	@repositoryName nvarchar(256),
	@maxReturn int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, 
						  ProcessDefinition_Process.DescriptionSnippet, MruProcess.LastAccessDate
	FROM         ProcessDefinition_Process INNER JOIN
								  (SELECT     TOP (@maxReturn) MAX(ProcessDefinition_Access.DateAccessed) AS LastAccessDate, ProcessDefinition_Access.ProcessId
	FROM         ProcessDefinition_Access INNER JOIN
						  ProcessDefinition_Process AS ProcessDefinition_Process_1 ON ProcessDefinition_Access.ProcessId = ProcessDefinition_Process_1.ProcessId INNER JOIN
						  ProcessDefinition_Repository AS ProcessDefinition_Repository_1 ON ProcessDefinition_Process_1.ForeignId = ProcessDefinition_Repository_1.RepositoryId
	WHERE     (ProcessDefinition_Repository_1.RepositoryName = @repositoryName) AND (ProcessDefinition_Access.UserId = @userId)  AND IsDeleted=0
	GROUP BY ProcessDefinition_Access.ProcessId
ORDER BY LastAccessDate DESC) AS MruProcess ON ProcessDefinition_Process.ProcessId = MruProcess.ProcessId
	ORDER BY MruProcess.LastAccessDate DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_GetEmailTemplates]'
GO


 
 
CREATE PROCEDURE [dbo].[Email_GetEmailTemplates]
WITH ENCRYPTION AS
BEGIN
 
			SET NOCOUNT ON;
 
SELECT     TemplateName, EmailSubject, EmailBody, SubstitutionsAvailable, ToAddress, CcAddress, FromAddress, EmailTemplateId, BccAddress, ReadReceipt
FROM         Email_EmailTemplate

END





GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLicensedUsers]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLicensedUsers]
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;


SELECT     ProcessDefinition_License.LicenseId, ProcessDefinition_License.Info, Account_User.UserId, Account_User.DisplayName, Account_User.MemberEmailAddress, 
                      Account_User.LicenseId AS UserLicenseId, ProcessDefinition_License.Feature, ProcessDefinition_License.ValidTo, 
                      CurrentLicensesInUse.Expiry AS CurrentLicenseExpiry, CurrentLicensesInUse.Info AS CurrentLicenseInfo
FROM         Account_User LEFT OUTER JOIN
                          (SELECT     ProcessDefinition_LicenseUser.UserId, ProcessDefinition_LicenseUser.LicenseId, ProcessDefinition_LicenseUser.Expiry, 
                                                   ProcessDefinition_License_1.Info
                            FROM          ProcessDefinition_LicenseUser INNER JOIN
                                                   ProcessDefinition_License AS ProcessDefinition_License_1 ON ProcessDefinition_LicenseUser.LicenseId = ProcessDefinition_License_1.LicenseId) 
                      AS CurrentLicensesInUse ON Account_User.UserId = CurrentLicensesInUse.UserId LEFT OUTER JOIN
                      ProcessDefinition_License ON Account_User.LicenseId = ProcessDefinition_License.LicenseId
					  WHERE Account_User.IsDeleted=0
					  ORDER BY Account_User.DisplayName


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ActiveProject]'
GO
CREATE TABLE [dbo].[ProcessDefinition_ActiveProject]
(
[ActiveProjectId] [int] NOT NULL IDENTITY(1, 1),
[RepositoryId] [int] NOT NULL,
[ProjectId] [int] NOT NULL,
[UserId] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_ActiveProject] on [dbo].[ProcessDefinition_ActiveProject]'
GO
ALTER TABLE [dbo].[ProcessDefinition_ActiveProject] ADD CONSTRAINT [PK_ProcessDefinition_ActiveProject] PRIMARY KEY CLUSTERED  ([ActiveProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ActiveProject_RepositoryId] on [dbo].[ProcessDefinition_ActiveProject]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ActiveProject_RepositoryId] ON [dbo].[ProcessDefinition_ActiveProject] ([RepositoryId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ActiveProject_ProjectId] on [dbo].[ProcessDefinition_ActiveProject]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ActiveProject_ProjectId] ON [dbo].[ProcessDefinition_ActiveProject] ([ProjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_ProcessDefinition_ActiveProject_UserId] on [dbo].[ProcessDefinition_ActiveProject]'
GO
CREATE NONCLUSTERED INDEX [IX_ProcessDefinition_ActiveProject_UserId] ON [dbo].[ProcessDefinition_ActiveProject] ([UserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetActiveProject]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetActiveProject] 
	@repositoryName nvarchar(256),
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_Project.ProjectId, ProcessDefinition_Project.ProjectName, ProcessDefinition_ProjectMember.ProjectMemberRole
	FROM         ProcessDefinition_ActiveProject INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ActiveProject.ProjectId = ProcessDefinition_Project.ProjectId LEFT OUTER JOIN
						  ProcessDefinition_ProjectMember ON ProcessDefinition_ActiveProject.UserId = ProcessDefinition_ProjectMember.UserId AND 
						  ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectMember.ProjectId
	WHERE     (ProcessDefinition_ActiveProject.UserId = @userId) AND (ProcessDefinition_ActiveProject.RepositoryId = @RepositoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryMruProcessesFull]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryMruProcessesFull]
	@repositoryName nvarchar(256),
	@maxReturn int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @accessedSince dateTime
	SET @accessedSince=DATEADD(month,-1,GetUtcDate())

	SELECT     ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, 
						  ProcessDefinition_Process.DescriptionSnippet, MruProcess.LastAccessDate, ProcessDefinition_Process.ProcessDescription
	FROM         ProcessDefinition_Process INNER JOIN
								  (SELECT     TOP (@maxReturn) ProcessDefinition_Access.ProcessId, MAX(ProcessDefinition_Access.DateAccessed) AS LastAccessDate
FROM         ProcessDefinition_Access INNER JOIN
                      ProcessDefinition_Process AS ProcessDefinition_Process_1 ON ProcessDefinition_Access.ProcessId = ProcessDefinition_Process_1.ProcessId INNER JOIN
                      ProcessDefinition_Repository AS ProcessDefinition_Repository_1 ON ProcessDefinition_Process_1.ForeignId = ProcessDefinition_Repository_1.RepositoryId
WHERE     (ProcessDefinition_Repository_1.RepositoryName = @repositoryName) AND (ProcessDefinition_Access.UserId = @userId) AND 
                      (ProcessDefinition_Access.DateAccessed > @accessedSince) AND IsDeleted=0
GROUP BY ProcessDefinition_Access.ProcessId
ORDER BY LastAccessDate DESC,COUNT(ProcessDefinition_Access.ProcessAccessId) DESC) AS MruProcess ON ProcessDefinition_Process.ProcessId = MruProcess.ProcessId
	ORDER BY MruProcess.LastAccessDate DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Email_UpdateEmailTemplate]'
GO


 
 
CREATE PROCEDURE [dbo].[Email_UpdateEmailTemplate]
(
	@EmailTemplateId int,
	@EmailSubject nvarchar(255),
	@EmailBody nvarchar(max),
	@ToAddress nvarchar(512),
	@CcAddress nvarchar(512),
	@FromAddress nvarchar(512),
	@BccAddress nvarchar(512),
	@ReadReceipt nvarchar(512)
)
WITH ENCRYPTION AS
BEGIN
 
			SET NOCOUNT ON;
 
	UPDATE Email_EmailTemplate SET
		EmailSubject=@EmailSubject, 
		EmailBody=@EmailBody, 
		ToAddress=@ToAddress, 
		CcAddress=@CcAddress, 
		FromAddress=@FromAddress,
		BccAddress=@BccAddress,
		ReadReceipt=@ReadReceipt
	 WHERE EmailTemplateId=@EmailTemplateId
END






GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AssignUserLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_AssignUserLicense]
	@userId int,
	@licenseId int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	UPDATE Account_User
	SET LicenseId = @licenseId
	WHERE UserId = @userId

		exec ProcessDefinition_CleanupUserLicenseSessions @userId, @licenseId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUserProjects]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetUserProjects] 
	@repositoryName nvarchar(256),
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @MemberRole int
	SELECT  @MemberRole=MemberRole
	FROM         ProcessDefinition_Member
	WHERE     (RepositoryId = @RepositoryId) AND (UserId = @userId)

	SELECT     ProjectId, ProjectName
	FROM         ProcessDefinition_Project
	WHERE     (RepositoryId = @RepositoryId) AND (@MemberRole>=3)
	UNION
	SELECT     ProcessDefinition_Project.ProjectId, ProcessDefinition_Project.ProjectName
	FROM         ProcessDefinition_ProjectMember INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectMember.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND (ProcessDefinition_ProjectMember.UserId = @userId)
	AND (@MemberRole<3)
	ORDER BY ProjectName

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetCurrentUserLicenses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetCurrentUserLicenses]
	@userId int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

SELECT     Account_User.LicenseId, ProcessDefinition_LicenseUser.UserId, ProcessDefinition_LicenseUser.Expiry, ProcessDefinition_License.Validation, 
                      ProcessDefinition_License.ValidationCode
FROM         Account_User INNER JOIN
                      ProcessDefinition_License ON Account_User.LicenseId = ProcessDefinition_License.LicenseId LEFT OUTER JOIN
                      ProcessDefinition_LicenseUser ON Account_User.LicenseId = ProcessDefinition_LicenseUser.LicenseId
	WHERE Account_User.UserId = @userId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetActiveProject]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetActiveProject] 
		@repositoryName nvarchar(256),
	@projectId int, 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	IF(@projectId IS NULL)
	BEGIN
		DELETE FROM ProcessDefinition_ActiveProject
		WHERE     (RepositoryId = @RepositoryId) AND (UserId = @userId)
	END
	ELSE
	BEGIN
		DECLARE @activeProjectId int
		SELECT     @activeProjectId=ActiveProjectId
		FROM         ProcessDefinition_ActiveProject
		WHERE     (UserId = @userId) AND (RepositoryId = @RepositoryId)

		IF(dbo.ProcessDefinition_HasProjectAccess(@projectId,@userId)=1)
		BEGIN
			IF(@activeProjectId IS NULL)
			BEGIN

				INSERT INTO ProcessDefinition_ActiveProject
									  (RepositoryId, ProjectId, UserId)
				VALUES     (@RepositoryId,@projectId,@userId)

			END
			ELSE
			BEGIN
				UPDATE    ProcessDefinition_ActiveProject
				SET              ProjectId = @projectId
				WHERE     (ActiveProjectId = @activeProjectId)
			END
		END
	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessProcessType]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessProcessType]
		@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.ProcessTypeId, ProcessDefinition_ProcessType.ProcessTypeName
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_ProcessType ON ProcessDefinition_Process.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
	WHERE     (ProcessDefinition_Process.ProcessId = @processId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessProcessType]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessProcessType]
		@processId int,
	@processTypeId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_Process
	SET ProcessDefinition_Process.ProcessTypeId = @processTypeId
	WHERE     (ProcessDefinition_Process.ProcessId = @processId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetMandatoryRoles]'
GO
CREATE PROCEDURE [dbo].[Account_GetMandatoryRoles] 
		@userType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Account_DotNetRole.DotNetRoleId, Account_DotNetRole.RoleName
	FROM         Account_UserRoleMapping INNER JOIN
						  Account_DotNetRole ON Account_UserRoleMapping.DotNetRoleId = Account_DotNetRole.DotNetRoleId
	WHERE     (Account_UserRoleMapping.PrimaryUserTypeId = @userType) AND (Account_UserRoleMapping.IsMandatory = 1)
	ORDER BY Account_DotNetRole.RoleName
END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AddCurrentUserLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_AddCurrentUserLicense]
	@userId int,
	@validationCode varchar(50),
	@expiry DateTime,
	@sessionToken varchar(32)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @licenseId int
	SELECT @licenseId  = LicenseId
	FROM ProcessDefinition_License
	WHERE ValidationCode = @validationCode

	IF(NOT(@licenseId IS NULL))
	BEGIN
				exec ProcessDefinition_CleanupUserLicenseSessions @userId, NULL

		INSERT INTO ProcessDefinition_LicenseUser(UserId, LicenseId, Expiry, Session)
		VALUES(@userId, @licenseId, @expiry, @sessionToken)
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetStepPredecessors]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetStepPredecessors] 
	@ParentProcessId int,
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	

	DECLARE @CorrectProcessHistoryId int
	SELECT @CorrectProcessHistoryId =  ProcessHistoryId
	FROM ProcessDefinition_ProcessHistory
	WHERE   (ProcessDefinition_ProcessHistory.ProcessId = @ParentProcessId) AND
		 ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))

	SELECT StepPredecessorHistoryId, StepPredecessorId, ParentProcessId, ProcessStepId, StepUId, FromProcessStepId, FromStepUId, PredecessorText, ProcessHistoryId
	FROM  ProcessDefinition_StepPredecessorHistory WHERE (ProcessHistoryId = @CorrectProcessHistoryId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetCurrentUserLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetCurrentUserLicense]
	@userId int,
	@sessionToken varchar(32)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

SELECT     ProcessDefinition_LicenseUser.LicenseId, ProcessDefinition_LicenseUser.Expiry, ProcessDefinition_License.Validation, 
                      ProcessDefinition_License.ValidationCode
FROM         ProcessDefinition_LicenseUser INNER JOIN
                      ProcessDefinition_License ON ProcessDefinition_LicenseUser.LicenseId = ProcessDefinition_License.LicenseId
WHERE     (ProcessDefinition_LicenseUser.UserId = @userId) AND (ProcessDefinition_LicenseUser.Session = @sessionToken)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_RepositoryAccess]'
GO
CREATE PROCEDURE [dbo].[Report_RepositoryAccess] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)


	SELECT     CAST(DATEPART(year, ProcessDefinition_Access.DateAccessed) AS nvarchar) + '-' + CAST(DATEPART(month, ProcessDefinition_Access.DateAccessed) AS nvarchar) 
						  AS dd_Month, ProcessDefinition_Process.ProcessTitle AS tf_Process, COUNT(DISTINCT ProcessDefinition_Access.UserId) AS n_UserAccesses
	FROM         ProcessDefinition_Access INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_Access.ProcessId = ProcessDefinition_Process.ProcessId
	WHERE ProcessDefinition_Process.ForeignId=@RepositoryId AND IsDeleted=0
	GROUP BY ProcessDefinition_Process.ProcessTitle, CAST(DATEPART(year, ProcessDefinition_Access.DateAccessed) AS nvarchar) + '-' + CAST(DATEPART(month, 
						  ProcessDefinition_Access.DateAccessed) AS nvarchar)
	ORDER BY dd_Month DESC, n_UserAccesses DESC, tf_Process

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectMembers]'
GO



 
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectMembers]
	@projectId int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

SELECT     ProcessDefinition_ProjectMember.ProjectMemberId, ProcessDefinition_ProjectMember.UserId, ProcessDefinition_ProjectMember.ProjectMemberRole, 
                      Account_User.DisplayName, Account_User.MemberEmailAddress, CAST('' AS varchar(256)) AS GravatarUrl, ProcessDefinition_ProjectMember.ForceFilteredView
FROM         ProcessDefinition_ProjectMember INNER JOIN
                      Account_User ON ProcessDefinition_ProjectMember.UserId = Account_User.UserId
WHERE     (ProcessDefinition_ProjectMember.ProjectId = @projectId) AND (Account_User.IsDeleted=0)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_RepositoryUserAccess]'
GO
CREATE PROCEDURE [dbo].[Report_RepositoryUserAccess] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     CAST(DATEPART(year, ProcessDefinition_Access.DateAccessed) AS nvarchar) + '-' + CAST(DATEPART(month, ProcessDefinition_Access.DateAccessed) AS nvarchar) 
                      AS dd_Month, Account_User.DisplayName AS tf_Name, Account_User.MemberEmailAddress AS tf_Email, COUNT(DISTINCT ProcessDefinition_Access.ProcessId) 
                      AS n_ProcessesViewed
FROM         ProcessDefinition_Access INNER JOIN
                      Account_User ON ProcessDefinition_Access.UserId = Account_User.UserId INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_Access.ProcessId = ProcessDefinition_Process.ProcessId
	WHERE ProcessDefinition_Process.ForeignId=@RepositoryId
GROUP BY ProcessDefinition_Access.UserId, CAST(DATEPART(year, ProcessDefinition_Access.DateAccessed) AS nvarchar) + '-' + CAST(DATEPART(month, 
                      ProcessDefinition_Access.DateAccessed) AS nvarchar), Account_User.DisplayName, Account_User.MemberEmailAddress
ORDER BY dd_Month DESC, n_ProcessesViewed DESC, tf_Name

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateDiscussion]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateDiscussion]
(
     @DiscussionId int,
	 @DiscussionText nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     UPDATE ProcessDefinition_Discussion SET DiscussionText=@DiscussionText
	  WHERE DiscussionId=@DiscussionId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_OpenComment]'
GO
CREATE TABLE [dbo].[Notes_OpenComment]
(
[OpenCommentId] [int] NOT NULL IDENTITY(1, 1),
[ForeignType] [int] NOT NULL,
[ForeignId] [int] NOT NULL,
[DisplayName] [nvarchar] (255) NOT NULL,
[EmailAddress] [nvarchar] (512) NULL,
[CommentText] [nvarchar] (max) NOT NULL,
[DateTimeLogged] [datetime] NOT NULL CONSTRAINT [DF_Notes_OpenComment_DateTimeLogged] DEFAULT (getutcdate())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Notes_OpenComment] on [dbo].[Notes_OpenComment]'
GO
ALTER TABLE [dbo].[Notes_OpenComment] ADD CONSTRAINT [PK_Notes_OpenComment] PRIMARY KEY CLUSTERED  ([OpenCommentId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_OpenComment_ForeignType] on [dbo].[Notes_OpenComment]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_OpenComment_ForeignType] ON [dbo].[Notes_OpenComment] ([ForeignType])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_Notes_OpenComment_ForeignId] on [dbo].[Notes_OpenComment]'
GO
CREATE NONCLUSTERED INDEX [IX_Notes_OpenComment_ForeignId] ON [dbo].[Notes_OpenComment] ([ForeignId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_CreateOpenComment]'
GO
 
 
CREATE PROCEDURE [dbo].[Notes_CreateOpenComment]
(
     @foreignType int,
      @foreignId int,
      @DisplayName nvarchar(255),
      @EmailAddress nvarchar(512),
      @CommentText nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO Notes_OpenComment
      (
            ForeignType, 
            ForeignId, 
            DisplayName, 
            EmailAddress, 
            CommentText
      ) VALUES (
            @foreignType, 
            @foreignId, 
            @DisplayName, 
            @EmailAddress, 
            @CommentText
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetStepHierarchy]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetStepHierarchy] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


WITH FlatSteps (ParentProcessId, ParentStepId,ProcessStepId, ChildProcessId, ProcessTitle,StepPosition, StepType)
AS
(

SELECT     ProcessDefinition_Step.ParentProcessId, 1 AS ParentStepId,ProcessDefinition_Step.ProcessStepId, ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.ProcessTitle, 
                      ProcessDefinition_Step.StepPosition, ProcessDefinition_Step.StepType
FROM         ProcessDefinition_Step INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_Step.ChildProcessId = ProcessDefinition_Process.ProcessId
WHERE     (ProcessDefinition_Step.ParentProcessId = @processId)

    UNION ALL

SELECT     ProcessDefinition_Step.ParentProcessId, FlatSteps.ProcessStepId AS ParentStepId, ProcessDefinition_Step.ProcessStepId, ProcessDefinition_Process.ProcessId, 
                      ProcessDefinition_Process.ProcessTitle,ProcessDefinition_Step.StepPosition, ProcessDefinition_Step.StepType
FROM         ProcessDefinition_Step INNER JOIN
                      ProcessDefinition_Process ON ProcessDefinition_Step.ChildProcessId = ProcessDefinition_Process.ProcessId
		INNER JOIN FlatSteps ON FlatSteps.ChildProcessId=ProcessDefinition_Step.ParentProcessId
)
SELECT   0 AS ParentProcessId,0 AS ParentStepId, 1 AS ProcessStepId,  ProcessId AS ChildProcessId, ProcessTitle,0 AS StepPosition,0 AS StepType
FROM         ProcessDefinition_Process
WHERE     (ProcessId = @processId)

UNION
SELECT ParentProcessId, ParentStepId,ProcessStepId, ChildProcessId, ProcessTitle,StepPosition, StepType FROM FlatSteps ORDER BY ParentProcessId,StepPosition



END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_UpdateOpenComment]'
GO
 
 
CREATE PROCEDURE [dbo].[Notes_UpdateOpenComment]
(
     @OpenCommentId int,
      @CommentText nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     UPDATE Notes_OpenComment SET
            CommentText=@CommentText
       WHERE OpenCommentId=@OpenCommentId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_DeleteOpenComment]'
GO
 
 
CREATE PROCEDURE [dbo].[Notes_DeleteOpenComment]
(
     @OpenCommentId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     DELETE FROM Notes_OpenComment WHERE OpenCommentId=@OpenCommentId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SavedProcess]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_SavedProcess] 
	@processId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @historyId int
	DECLARE @previousHistoryId int
	
	SELECT @previousHistoryId  = ProcessHistoryId 
	FROM ProcessDefinition_ProcessHistory
	WHERE  ProcessId = @processId AND IsLatestVersion = 1
	
		DECLARE @IsFrozenVersion bit
	SET @IsFrozenVersion = 0

	DECLARE @DateFrozen datetime
	SELECT @DateFrozen=DateFrozen
		FROM         ProcessDefinition_Process
		WHERE     (ProcessId = @processId)

	DECLARE @hasPreviouslyFrozen int
	SELECT @hasPreviouslyFrozen = COUNT(ProcessHistoryId) 
	FROM ProcessDefinition_ProcessHistory
	WHERE ProcessId=@processId AND (NOT(DateFrozen IS NULL))

	IF(NOT(@DateFrozen IS NULL) OR (@hasPreviouslyFrozen = 0) )
	BEGIN
				
		UPDATE ProcessDefinition_ProcessHistory
			SET IsFrozenVersion = 0, IsLatestVersion = 0
			WHERE     (ProcessId = @processId) 
		SET @IsFrozenVersion = 1
	END
	ELSE
	BEGIN
				UPDATE ProcessDefinition_ProcessHistory
			SET IsLatestVersion = 0
			WHERE     (ProcessId = @processId) 
	END

		UPDATE ProcessDefinition_Process
	SET UserId =  @userId
	WHERE (ProcessId = @processId)

	INSERT INTO ProcessDefinition_ProcessHistory
						  (ProcessId, ForeignType, ForeignId, DateCreated, ProcessDescription, ProcessTitle, IsPublished, DateUpdated, 
						DefaultTags,DescriptionSnippet, MajorVersion, MinorVersion, PrettyPostTitle, UserId, ProcessTypeId, DateFrozen, 
						IsFrozenVersion, IsLatestVersion, AltGroup, RelationshipGraph, IsDeleted,StepDefinitionVersion, StepsSvg)
	SELECT     ProcessId, ForeignType, ForeignId, DateCreated, ProcessDescription, ProcessTitle, IsPublished, DateUpdated, DefaultTags, DescriptionSnippet, MajorVersion, 
						  MinorVersion, PrettyPostTitle, UserId, ProcessTypeId, DateFrozen, @IsFrozenVersion, 1, AltGroup, RelationshipGraph, 
						  IsDeleted,StepDefinitionVersion, StepsSvg
	FROM         ProcessDefinition_Process
	WHERE     (ProcessId = @processId)
	SET @historyId = Scope_Identity()

		INSERT INTO ProcessDefinition_StepHistory(ProcessStepId, ParentProcessId, StepName, StepDescription, ChildProcessId, StepPosition, 
		StepType, IterationDescription, OptionalDescription, MajorVersion, MinorVersion,ProcessHistoryId, bpmnJson)
	SELECT     ProcessDefinition_Step.ProcessStepId, ProcessDefinition_Step.ParentProcessId, ProcessDefinition_Step.StepName, ProcessDefinition_Step.StepDescription, 
						  ProcessDefinition_Step.ChildProcessId, ProcessDefinition_Step.StepPosition, ProcessDefinition_Step.StepType, ProcessDefinition_Step.IterationDescription, 
						  ProcessDefinition_Step.OptionalDescription, ProcessDefinition_Process.MajorVersion, ProcessDefinition_Process.MinorVersion,@historyId,
						  bpmnJson
	FROM         ProcessDefinition_Step INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_Step.ParentProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ParentProcessId = @processId)

		INSERT INTO ProcessDefinition_StepPredecessorHistory 
	(StepPredecessorId, ParentProcessId, ProcessStepId, StepUId, FromProcessStepId, FromStepUId, PredecessorText,ProcessHistoryId)
	SELECT StepPredecessorId, ParentProcessId, ProcessStepId, StepUId, FromProcessStepId, FromStepUId, PredecessorText,@historyId
	FROM  ProcessDefinition_StepPredecessor WHERE ParentProcessId=@processId


		INSERT INTO ProcessDefinition_ProcessLinkHistory(ProcessId, SectionName, LinkUri, LinksToProcessId, FullLinkUri, LinkText, 
		MajorVersion, MinorVersion,ProcessHistoryId, LinkType, LinkUid, SectionDirection, SectionMultiplicity, SectionType, SectionLinkTypeId, ExcludedLinksToProcessId)
	SELECT     ProcessDefinition_ProcessLink.ProcessId, ProcessDefinition_ProcessLink.SectionName, 
						  ProcessDefinition_ProcessLink.LinkUri, ProcessDefinition_ProcessLink.LinksToProcessId, ProcessDefinition_ProcessLink.FullLinkUri, 
						  ProcessDefinition_ProcessLink.LinkText, ProcessDefinition_Process.MajorVersion, ProcessDefinition_Process.MinorVersion,@historyId,
							LinkType, LinkUid, SectionDirection, SectionMultiplicity, SectionType, SectionLinkTypeId, ExcludedLinksToProcessId
	FROM         ProcessDefinition_ProcessLink INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProcessLink.ProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_ProcessLink.ProcessId = @processId)

		INSERT INTO dbo.Metadata_MetadataField( ForeignId, ForeignType, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, 
		CssClass, FormatInfo, ControlData, IsDeleted, UniqueId
	)
	SELECT     @historyId, 18, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, CssClass, FormatInfo, ControlData, Metadata_MetadataField.IsDeleted, UniqueId
	FROM         ProcessDefinition_Process INNER JOIN
						  Metadata_MetadataField ON ProcessDefinition_Process.ProcessTypeId = Metadata_MetadataField.ForeignId
	WHERE     (Metadata_MetadataField.ForeignType = 17) AND (ProcessDefinition_Process.ProcessId = @processId)  AND (Metadata_MetadataField.IsDeleted=0)

		INSERT INTO dbo.Metadata_MetadataField( ForeignId, ForeignType, MetadataType, IsMandatory, Position,  ScreenLabel, DefaultValue, AllowableValues, CssClass, 
		FormatInfo, ControlData, IsDeleted, UniqueId
	)
	SELECT     @historyId, 16, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
						  Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
						  Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, Metadata_MetadataField.IsDeleted, UniqueId                  
	FROM         Metadata_MetadataField 
	WHERE (Metadata_MetadataField.ForeignType = 7)  AND Metadata_MetadataField.ForeignId=@processId AND (IsDeleted=0)

		INSERT INTO dbo.Metadata_MetadataField( ForeignId, ForeignType, MetadataType, IsMandatory, Position,  ScreenLabel, DefaultValue, AllowableValues, CssClass, 
		FormatInfo, ControlData, IsDeleted, UniqueId
	)
	SELECT     @historyId, 19, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
						  Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
						  Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, Metadata_MetadataField.IsDeleted, UniqueId                  
	FROM         Metadata_MetadataField 
	WHERE (Metadata_MetadataField.ForeignType = 10)  AND Metadata_MetadataField.ForeignId=@processId AND (IsDeleted=0)
	
				INSERT INTO dbo.Metadata_Data([MetadataId] ,[ForeignId] ,[ForeignType],[StringValue]
      ,[IntValue]      ,[BoolValue]      ,[DoubleValue]      ,[DateValue]      ,[IsDeleted]
      ,[DateChanged]      ,[ChangedByUserId]
		)
		SELECT     Metadata_Data.MetadataId, 
		ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId, 
			21, 
		Metadata_Data.StringValue, 
		Metadata_Data.IntValue, 
		Metadata_Data.BoolValue, 
		Metadata_Data.DoubleValue, 
        Metadata_Data.DateValue, 
		Metadata_Data.IsDeleted, 
		Metadata_Data.DateChanged, 
		Metadata_Data.ChangedByUserId
		FROM         Metadata_Data INNER JOIN
							  ProcessDefinition_ProcessLinkData ON Metadata_Data.ForeignId = ProcessDefinition_ProcessLinkData.ProcessLinkDataId INNER JOIN
							  ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_ProcessLinkData.LinkUid = ProcessDefinition_ProcessLinkHistory.LinkUid
		WHERE     (Metadata_Data.ForeignType = 20) AND 
			(ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @historyId) AND
			(ProcessDefinition_ProcessLinkData.ProcessId = @processId)
				AND (IsDeleted=0)

		UPDATE Metadata_Data
	SET MetadataId = x.NewMetadataId
FROM (
SELECT     Metadata_Data.MetadataId AS OldMetadataId, NewMetadataId.MetadataId AS NewMetadataId
FROM         Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                          (
SELECT     MetadataId, UniqueId
                            FROM          Metadata_MetadataField AS Metadata_MetadataField_1
                            WHERE      (ForeignId = @historyId) AND (ForeignType = 19)) AS NewMetadataId ON Metadata_MetadataField.UniqueId = NewMetadataId.UniqueId

WHERE     
Metadata_Data.ForeignType = 21  AND
Metadata_MetadataField.ForeignId = @previousHistoryId AND 
Metadata_MetadataField.ForeignType = 19 
) as x

WHERE Metadata_Data.MetadataId=x.OldMetadataId AND Metadata_Data.ForeignType = 21 


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProjectPlanTask]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProjectPlanTask]
(
	@TaskName nvarchar(256),
	@ParentTaskId int,
	@TaskGuid nvarchar(50),
	@TaskProcessId int,
	@TaskStepId int,
	@TaskOptional bit,
	@TaskIterative bit,
	@TaskConcurrent bit,
	@TaskIsRemoved bit,
	@TaskBasedOnGuid nvarchar(50),
	@projectPlanId int,
	@TaskNotes nvarchar(max),
	@TaskPosition int,
	@TaskType int,
	@userId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @processHistoryId int
	SET @processHistoryId=NULL

	 IF @TaskProcessId IS NOT NULL
	 BEGIN	
		SELECT     @processHistoryId=ProcessHistoryId
		FROM         ProcessDefinition_ProjectProcessVersion
		WHERE     (ProjectPlanId = @projectPlanId) AND (ProcessId = @TaskProcessId)
	 END
 

	INSERT INTO ProcessDefinition_ProjectPlanTask
						  (TaskName, ParentTaskId, TaskGuid, TaskProcessId, TaskStepId, TaskOptional, TaskIterative, TaskConcurrent, TaskIsRemoved, TaskBasedOnGuid, ProjectPlanId, 
						  TaskNotes, TaskPosition, TaskType, ProcessHistoryId, RemovalReason, EditorUserId)
	VALUES     (@TaskName,@ParentTaskId,@TaskGuid,@TaskProcessId,@TaskStepId,@TaskOptional,@TaskIterative,@TaskConcurrent,@TaskIsRemoved,@TaskBasedOnGuid,@projectPlanId,
						   ISNULL(@TaskNotes, ''),@TaskPosition,@TaskType,@processHistoryId, '',@userId) 
     DECLARE @newId int
     SET @newId = Scope_Identity()

		INSERT INTO ProcessDefinition_ProjectPlanTaskLink(TaskId, LinksToProcessHistoryId, LinksToProcessId, ProcessLinkHistoryId)
	SELECT     @newId, ProcessDefinition_ProjectProcessVersion.ProcessHistoryId,
	ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
	FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
						  ProcessDefinition_ProjectProcessVersion ON ProcessDefinition_ProcessLinkHistory.LinksToProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId
	WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @processHistoryId) AND (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)



     RETURN @newId
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaggedProcessListByReposName]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaggedProcessListByReposName] 
	@repositoryName nvarchar(256),
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	IF(@useFrozen = 0)
	BEGIN
		SELECT     ISNULL(Notes_Tag.TagName,'untagged') AS TagName, ISNULL(Notes_Tag.TagId,0) AS TagId, 
			ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle,ProcessDefinition_Process.ProcessTypeId
		FROM         ProcessDefinition_Repository INNER JOIN
							  ProcessDefinition_Process ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_Process.ForeignId LEFT OUTER JOIN
							  Notes_Tag INNER JOIN
							  Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId ON ProcessDefinition_Process.ProcessId = Notes_AssignedTag.ForeignId
		WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted=0
		ORDER BY Notes_Tag.TagName, ProcessDefinition_Process.ProcessTitle
	END
	ELSE
	BEGIN
		SELECT ISNULL(Notes_Tag.TagName, 'untagged') AS TagName, ISNULL(Notes_Tag.TagId, 0) AS TagId, FrozenProcesses.ProcessId, FrozenProcesses.ProcessTitle, FrozenProcesses.PrettyPostTitle, FrozenProcesses.ProcessTypeId
		FROM  ProcessDefinition_Repository INNER JOIN
					 (SELECT ProcessId, ProcessTitle, PrettyPostTitle, ForeignId, ProcessTypeId
					FROM  ProcessDefinition_ProcessHistory
					WHERE (IsFrozenVersion = 1)) AS FrozenProcesses ON ProcessDefinition_Repository.RepositoryId = FrozenProcesses.ForeignId INNER JOIN
				 ProcessDefinition_Process ON FrozenProcesses.ProcessId = ProcessDefinition_Process.ProcessId LEFT OUTER JOIN
				 Notes_Tag INNER JOIN
				 Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId ON FrozenProcesses.ProcessId = Notes_AssignedTag.ForeignId
		WHERE (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND (ProcessDefinition_Process.IsDeleted = 0)
		ORDER BY TagName, FrozenProcesses.ProcessTitle
	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetOpenComment]'
GO
 
 
CREATE PROCEDURE [dbo].[Notes_GetOpenComment]
(
     @OpenCommentId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     SELECT ForeignType, 
            ForeignId, 
            DisplayName, 
            EmailAddress, 
            CommentText, 
            DateTimeLogged
            FROM Notes_OpenComment WHERE OpenCommentId=@OpenCommentId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AddChildStep]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_AddChildStep] 
	@processId int,
	@childProcessId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	DECLARE @processTitle nvarchar(256)
	SELECT     @processTitle=ProcessTitle
	FROM         ProcessDefinition_Process
	WHERE     (ProcessId = @childProcessId)

	DECLARE @stepPos int
	SELECT     @stepPos=ISNULL(MAX(StepPosition)+1,0)
	FROM         ProcessDefinition_Step
	WHERE     (ParentProcessId = @processId)

	INSERT INTO ProcessDefinition_Step
						  (ParentProcessId, StepName, StepDescription, ChildProcessId, StepPosition, StepType, IterationDescription, OptionalDescription)
	VALUES     (@processId,@processTitle, '',@childProcessId,@stepPos, 1, N'', N'')

	DECLARE @ret int
	SET @ret=Scope_Identity()
	RETURN @ret

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Notes_GetOpenComments]'
GO
 
 
CREATE PROCEDURE [dbo].[Notes_GetOpenComments]
(
	@foreignType int,
	@foreignId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
		SELECT     OpenCommentId, ForeignType, ForeignId, DisplayName, EmailAddress, CommentText, DateTimeLogged
		FROM         Notes_OpenComment
		WHERE     (ForeignType = @foreignType) AND (ForeignId = @foreignId)
		ORDER BY DateTimeLogged			
 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_UserLdap]'
GO
CREATE TABLE [dbo].[Account_UserLdap]
(
[MemberId] [uniqueidentifier] NOT NULL,
[LdapUserId] [nvarchar] (256) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_Account_UserLdap] on [dbo].[Account_UserLdap]'
GO
ALTER TABLE [dbo].[Account_UserLdap] ADD CONSTRAINT [PK_Account_UserLdap] PRIMARY KEY NONCLUSTERED  ([LdapUserId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_GetUserFromLdapUserId]'
GO
CREATE PROCEDURE [dbo].[Account_GetUserFromLdapUserId] 
		@ldapuid nvarchar(256)	
WITH ENCRYPTION AS
BEGIN
	SET NOCOUNT ON;

SELECT     Account_UserLdap.MemberId, Account_User.UserId, Account_User.DisplayName, Account_User.MemberEmailAddress, Account_User.Profile
FROM         Account_UserLdap INNER JOIN
                      Account_User ON Account_UserLdap.MemberId = Account_User.MemberId
WHERE     (UPPER(Account_UserLdap.LdapUserId) = UPPER(@ldapuid)) AND (Account_User.IsDeleted = 0)

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_MoveStep]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_MoveStep] 
	@movedStepId int, 
	@movedProcessId int,
	@movePos int,
	@relativeToStepId int,
	@relativeToProcessId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @ret int


	DECLARE @ParentProcessId int,@OldStepPosition int

	SELECT		@ParentProcessId=ParentProcessId, 
				@OldStepPosition=StepPosition
	FROM         ProcessDefinition_Step
	WHERE     (ProcessStepId = @movedStepId)


	IF(@movePos=0) 	BEGIN

		UPDATE ProcessDefinition_Step SET StepPosition=StepPosition-1
		WHERE     StepPosition>@OldStepPosition AND ParentProcessId=@ParentProcessId AND (ProcessStepId != @movedStepId)

		DECLARE @newStepPos int
		SELECT     @newStepPos=ISNULL(MAX(StepPosition)+1,0)
		FROM         ProcessDefinition_Step
		WHERE     (ParentProcessId = @relativeToProcessId)

		UPDATE ProcessDefinition_Step SET ParentProcessId=@relativeToProcessId,StepPosition=@newStepPos
		WHERE     (ProcessStepId = @movedStepId)
	END
	ELSE
	BEGIN

		UPDATE ProcessDefinition_Step SET StepPosition=StepPosition-1
		WHERE     StepPosition>@OldStepPosition AND ParentProcessId=@ParentProcessId AND (ProcessStepId != @movedStepId)

		DECLARE @RelParentProcessId int,@RelStepPosition int
		SELECT     @RelStepPosition=StepPosition, @RelParentProcessId=ParentProcessId
		FROM         ProcessDefinition_Step
		WHERE     (ProcessStepId = @relativeToStepId)		

		DECLARE @newPos int

		IF(@movePos=1) 		BEGIN
			SET @newPos=@RelStepPosition
		END
		ELSE
		IF(@movePos=2) 		BEGIN
			SET @newPos=@RelStepPosition+1
		END

		UPDATE ProcessDefinition_Step SET StepPosition=StepPosition+1
		WHERE     StepPosition>=@newPos AND ParentProcessId=@RelParentProcessId

		UPDATE ProcessDefinition_Step SET ParentProcessId=@RelParentProcessId,StepPosition=@newPos
		WHERE     (ProcessStepId = @movedStepId)

	END


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_AddUserFromLdapUserId]'
GO
CREATE PROCEDURE [dbo].[Account_AddUserFromLdapUserId] 
		@memberId uniqueidentifier,
	@ldapuid nvarchar(256)
WITH ENCRYPTION AS
BEGIN
	SET NOCOUNT ON;

IF NOT(EXISTS(SELECT MemberId FROM Account_UserLdap WHERE LdapUserId=@ldapuid))
BEGIN
	INSERT INTO Account_UserLdap(MemberId, LdapUserId)
	VALUES(@memberId, @ldapuid)
END

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLastPublishedId]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLastPublishedId]
    @RepositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @repositoryId int
	SET @repositoryId=dbo.ProcessDefinition_GetRepositoryId(@RepositoryName)

    DECLARE @lastPublishedId int

    SELECT MAX(PublishId) AS LastPublishId
    FROM  ProcessDefinition_Publish
    WHERE (RepositoryId = @repositoryId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProjectPlan]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProjectPlan]
(
     @projectId int,
      @ProjectPlanName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

		DECLARE @existingId int
	SELECT  @existingId=ProjectPlanId
	FROM         ProcessDefinition_ProjectPlan
	WHERE     (ProjectId = @projectId) AND (ProjectPlanName = @ProjectPlanName)

	 DECLARE @newId int
	SET @newId=0

	IF(@existingId IS NULL)
	BEGIN 

		 INSERT INTO ProcessDefinition_ProjectPlan
		  (
				ProjectId, 
				ProjectPlanName

		  ) VALUES (
				@projectId, 
				@ProjectPlanName
		  )

	 
		 SET @newId = Scope_Identity()

						DECLARE @RepositoryId int
		SELECT @RepositoryId=RepositoryId FROM ProcessDefinition_Project WHERE ProjectId=@projectId

		INSERT INTO ProcessDefinition_ProjectProcessVersion(ProjectPlanId, ProcessId, MajorVersion, MinorVersion,ProcessHistoryId)		
		SELECT     @newId, ProcessId, MajorVersion, MinorVersion, ProcessHistoryId
		FROM         ProcessDefinition_ProcessHistory
	    WHERE      (ForeignType = 7) AND (ForeignId = @RepositoryId) AND IsFrozenVersion=1

				INSERT INTO ProcessDefinition_ProjectProcessType(ProjectPlanId, ProcessTypeId, RepositoryId, ProcessTypeName, IsDeleted)
		SELECT   @newId,  ProcessTypeId, RepositoryId, ProcessTypeName, IsDeleted
		FROM         ProcessDefinition_ProcessType	
		WHERE 	RepositoryId=@RepositoryId

	END

     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetStepType]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetStepType] 
	@stepId int, 
	@stepType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE    ProcessDefinition_Step
	SET              StepType = @stepType
	WHERE     (ProcessStepId = @stepId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessXml]'
GO

CREATE FUNCTION [dbo].[ProcessDefinition_GetProcessXml] (
		@processId int 
)
RETURNS Xml
WITH ENCRYPTION AS
BEGIN

	DECLARE @latestHistoryId INT
	SELECT @latestHistoryId  = ProcessHistoryId 
	FROM ProcessDefinition_ProcessHistory
	WHERE  ProcessId = @processId AND IsLatestVersion = 1

		DECLARE @RetValue Xml
	
	SET @RetValue = 
		( SELECT     ProcessUId AS [id], 
		ProcessDescription AS [description],
		DateCreated AS [created],
		ProcessTitle AS [title],
		PrettyPostTitle AS [url],
		DateUpdated AS [updated],
		MinorVersion AS [revision],
		TypeUId AS [typeId],
		AltGroup AS [altGroup],
		ProcessDefinition_Process.IsDeleted AS [deleted],
		RelationshipGraph AS [relGraph],
		StepDefinitionVersion AS [defnVersion],
		StepsSvg AS [stepsSvg],

(SELECT     SectionName AS [section], 
		LinkUri AS [link],
		FullLinkUri as [fullLink], 		LinkText as [text],
		(SELECT ProcessUId FROM ProcessDefinition_Process WHERE ProcessId=LinksToProcessId) AS [linkedProcessId]
						FROM         ProcessDefinition_ProcessLink
WHERE     (ProcessId = @processId)
FOR XML PATH('link'), ROOT('links'), ELEMENTS, type),
		
(SELECT StepUId AS [id],    
		StepName AS [name], 
		StepDescription AS [description],
		StepPosition as [position],
		(SELECT ProcessUId FROM ProcessDefinition_Process WHERE ProcessId=ChildProcessId) AS [stepProcessId],
        CASE WHEN (StepType & 2) != 0 THEN 'true' END AS [concurrent],
        CASE WHEN (StepType & 4) != 0 THEN 'true' END AS [optional],
        CASE WHEN (StepType & 8) != 0 THEN 'true' END AS [iterative],
		StepType AS [stepType],
		bpmnJson
FROM         ProcessDefinition_Step
WHERE     (ParentProcessId = @processId)
FOR XML PATH('step'), ROOT('steps'), ELEMENTS, type),

(SELECT StepUId AS [id],    
		FromStepUId AS [fromid], 
		PredecessorText AS [text]
FROM         ProcessDefinition_StepPredecessor
WHERE     (ParentProcessId = @processId)
FOR XML PATH('predecessor'), ROOT('predecessors'), ELEMENTS, type),

(SELECT     TagName AS [name]
FROM         Notes_Tag INNER JOIN
                      Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId
WHERE     (Notes_AssignedTag.ForeignId = @processId)
FOR XML PATH('tag'), ROOT('tags'), ELEMENTS, type),


(SELECT UniqueId as [id],    
		ScreenLabel AS [label], 
		MetadataType AS [type],
		Position as [position],
		DefaultValue as [default],
		AllowableValues as [allowable],
		FormatInfo as [format],
		ControlData as [data]			
FROM         Metadata_MetadataField
WHERE     (ForeignId = @latestHistoryId AND ForeignType = 16)
FOR XML PATH('field'), ROOT('metadata'), ELEMENTS, type),

(SELECT UniqueId as [id],    
		ScreenLabel AS [label], 
		MetadataType AS [type],
		Position as [position],
		DefaultValue as [default],
		AllowableValues as [allowable],
		FormatInfo as [format],
		ControlData as [data]			
FROM         Metadata_MetadataField
WHERE     (ForeignId = @latestHistoryId AND ForeignType = 19)
FOR XML PATH('field'), ROOT('usageProperties'), ELEMENTS, type),


(
SELECT    Metadata_MetadataField.UniqueId as [id],
		  Metadata_Data.StringValue as [stringvalue], 
		  Metadata_Data.IntValue as [intvalue], 
		  Metadata_Data.BoolValue as [boolvalue], 
		  Metadata_Data.DoubleValue as [doublevalue], 
		  Metadata_Data.DateValue as [datevalue], 
		  Metadata_Data.DateChanged as [datechanged],
		  ProcessDefinition_ProcessLinkHistory.LinkUid as [linkUid]
FROM          Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON Metadata_Data.ForeignId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
		WHERE     (Metadata_Data.ForeignType = 21) AND 
			(ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @latestHistoryId ) AND Metadata_Data.IsDeleted =0
FOR XML PATH('field'), ROOT('usageData'), ELEMENTS, type)

	FROM         ProcessDefinition_Process INNER JOIN
                      ProcessDefinition_ProcessType ON ProcessDefinition_Process.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
	WHERE     (ProcessId = @processId)
	FOR XML PATH('process'), ELEMENTS, type)

	RETURN @RetValue
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessDefinition]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessDefinition] 
	@RepositoryId int,
	@domainRoot nvarchar(512)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT(
SELECT RepositoryName as [name],
	@domainRoot as [domain],

( SELECT TypeUId AS [id],
	ProcessTypeName AS [name],
	ProcessTypeTemplate AS [template],
	IsDeleted AS [deleted],


(SELECT UniqueId as [id],    
		ScreenLabel AS [label], 
		MetadataType AS [type],
		Position as [position],
		DefaultValue as [default],
		AllowableValues as [allowable],
		FormatInfo as [format],
		ControlData as [data]			
FROM         Metadata_MetadataField
WHERE     (ForeignId = ProcessTypeId AND ForeignType = 17)
FOR XML PATH('field'), ROOT('metadata'), ELEMENTS, type)

	FROM ProcessDefinition_ProcessType
	WHERE (RepositoryId=@RepositoryId)
FOR XML PATH('type'), ROOT('types'), ELEMENTS , type),
 		
( SELECT dbo.ProcessDefinition_GetProcessXml(ProcessId)
	FROM ProcessDefinition_Process
	WHERE ForeignId=@RepositoryId AND IsDeleted=0
FOR XML PATH(''), ROOT('processes'), ELEMENTS, type)

FROM ProcessDefinition_Repository
WHERE (RepositoryId=@RepositoryId)
FOR XML PATH('library'), ELEMENTS
) AS LibraryXml

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectMemberRole]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectMemberRole] 
		@userId int, 
	@projectId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	SELECT     RoleProcessId
	FROM         ProcessDefinition_ProjectMemberRole
	WHERE     (UserId = @userId) AND ProjectId = @projectId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetActiveProjectPlanTasks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetActiveProjectPlanTasks] 
	@projectId int,
	@projectPlanId int,
	@parentTaskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
						  ProcessDefinition_ProjectPlanTask.TaskGuid, ProcessDefinition_ProjectPlanTask.TaskProcessId, ProcessDefinition_ProjectPlanTask.TaskStepId, 
						  ProcessDefinition_ProjectPlanTask.TaskOptional, ProcessDefinition_ProjectPlanTask.TaskIterative, ProcessDefinition_ProjectPlanTask.TaskConcurrent, 
						  ProcessDefinition_ProjectPlanTask.TaskIsRemoved, ProcessDefinition_ProjectPlanTask.TaskBasedOnGuid, ProcessDefinition_ProjectPlanTask.ProjectPlanId, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.TaskNotes, ProcessDefinition_ProjectPlanTask.TaskPosition, 
						  ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, ProcessDefinition_ProjectPlanTask.ActualStartDate, 
						  ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, ProcessDefinition_ProjectPlanTask.StatusNotes, 
						  ProcessDefinition_ProjectPlanTask.TaskProgressPc, AltGroup
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProjectPlanTask.TaskProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectId = @projectId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
						  (ISNULL(ProcessDefinition_ProjectPlanTask.ParentTaskId, 0) = ISNULL(@parentTaskId, 0)) AND (ProcessDefinition_ProjectPlanTask.TaskIsRemoved = 0)
	ORDER BY ProcessDefinition_ProjectPlanTask.TaskPosition

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryNewProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryNewProcesses]
	@repositoryName nvarchar(256),
	@maxReturn int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     TOP (@maxReturn) ProcessDefinition_Process.ProcessId AS ProcessCount, 
						  ProcessDefinition_Process.DateCreated AS DateChanged, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, 
						  ProcessDefinition_Process.DescriptionSnippet,ProcessDefinition_Process.ProcessDescription
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND IsDeleted=0
	ORDER BY DateChanged DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanAccessRequirements]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanAccessRequirements] 
		@projectPlanId int,
	@processId int	
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	SELECT     VersionOfLinkedTo.ProcessTitle, VersionOfLinkedTo.ProcessId
FROM         ProcessDefinition_ProjectProcessType INNER JOIN
                      ProcessDefinition_ProcessHistory AS VersionOfLinkedTo ON ProcessDefinition_ProjectProcessType.ProcessTypeId = VersionOfLinkedTo.ProcessTypeId INNER JOIN
                      ProcessDefinition_ProjectProcessVersion INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_ProjectProcessVersion.ProcessId = ProcessDefinition_ProcessLinkHistory.ProcessId AND 
                      ProcessDefinition_ProjectProcessVersion.MajorVersion = ProcessDefinition_ProcessLinkHistory.MajorVersion AND 
                      ProcessDefinition_ProjectProcessVersion.MinorVersion = ProcessDefinition_ProcessLinkHistory.MinorVersion INNER JOIN
                      ProcessDefinition_ProjectProcessVersion AS VersionOfLinkedToForProject ON 
                      ProcessDefinition_ProcessLinkHistory.LinksToProcessId = VersionOfLinkedToForProject.ProcessId AND 
                      ProcessDefinition_ProjectProcessVersion.ProjectPlanId = VersionOfLinkedToForProject.ProjectPlanId ON 
                      VersionOfLinkedTo.ProcessHistoryId = VersionOfLinkedToForProject.ProcessHistoryId INNER JOIN
                      ProcessDefinition_RepositorySettings ON ProcessDefinition_ProjectProcessType.RepositoryId = ProcessDefinition_RepositorySettings.RepositoryId AND 
                      VersionOfLinkedTo.ProcessTypeId = ProcessDefinition_RepositorySettings.PersonProcessTypeId
WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessId = @processId) AND (ProcessDefinition_ProjectProcessType.ProjectPlanId = @projectPlanId) AND 
                      (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesByType]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesByType] 
		@ProcessTypeId int, 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.DescriptionSnippet, ProcessId, AltGroup
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId) AND (ProcessTypeId = @ProcessTypeId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositoryUpdatedProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositoryUpdatedProcesses]
	@repositoryName nvarchar(256),
	@maxReturn int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     TOP (@maxReturn) ProcessDefinition_Process.ProcessId AS ProcessCount, 
						  ProcessDefinition_Process.DateUpdated AS DateChanged, ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessTitle, 
						  ProcessDefinition_Process.DescriptionSnippet,ProcessDefinition_Process.ProcessDescription
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName)AND IsDeleted=0
	ORDER BY DateChanged DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaskStepHistory]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaskStepHistory] 
		@processId int, 
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	SELECT     ProcessDefinition_StepHistory.StepPosition, ProcessDefinition_StepHistory.StepName, ProcessDefinition_StepHistory.StepDescription, 
						  ProcessDefinition_StepHistory.ChildProcessId, ProcessDefinition_StepHistory.StepType, ProcessDefinition_StepHistory.IterationDescription, 
						  ProcessDefinition_StepHistory.OptionalDescription, ProcessDefinition_StepHistory.MajorVersion, ProcessDefinition_StepHistory.MinorVersion, 
						  ProcessDefinition_StepHistory.StepHistoryId, ProcessDefinition_StepHistory.ProcessStepId, ProcessDefinition_StepHistory.ProcessHistoryId, 
						  CHProcHist.ProcessHistoryId AS ChildProcessHistoryId
	FROM         ProcessDefinition_StepHistory INNER JOIN
						  ProcessDefinition_ProjectProcessVersion ON 
						  ProcessDefinition_StepHistory.ProcessHistoryId = ProcessDefinition_ProjectProcessVersion.ProcessHistoryId LEFT OUTER JOIN
							  (SELECT     ProcessId, ProcessHistoryId
								FROM          ProcessDefinition_ProjectProcessVersion AS ProcessDefinition_ProjectProcessVersion_1
								WHERE      (ProjectPlanId = @projectPlanId)) AS CHProcHist ON ProcessDefinition_StepHistory.ChildProcessId = CHProcHist.ProcessId
	WHERE     (ProcessDefinition_ProjectProcessVersion.ProcessId = @processId) AND (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)
	ORDER BY ProcessDefinition_StepHistory.StepPosition

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ProcessesByProcessType]'
GO
CREATE PROCEDURE [dbo].[Report_ProcessesByProcessType] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

SELECT     ProcessDefinition_ProcessType.ProcessTypeName dd_ProcessType, ProcessDefinition_Process.ProcessTitle,'~/' + ProcessDefinition_Process.PrettyPostTitle AS link_Process
FROM         ProcessDefinition_Process INNER JOIN
                      ProcessDefinition_ProcessType ON ProcessDefinition_Process.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId AND ProcessDefinition_Process.IsDeleted=0)
ORDER BY ProcessDefinition_ProcessType.ProcessTypeName, ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Utils_GetIntList]'
GO
CREATE FUNCTION [dbo].[Utils_GetIntList] 
(	
	@startVal int,
	@maxVal int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(


WITH NCount(n)
AS (
    SELECT  @startVal
 
    UNION ALL
 
    SELECT  n + 1
    FROM    NCount
    WHERE   n < @maxVal
)
SELECT  n
FROM    NCount

)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Utils_DateWeekBlocksOverLastYear]'
GO
CREATE FUNCTION [dbo].[Utils_DateWeekBlocksOverLastYear]
(
	@dateFrom DateTime
)
RETURNS @WeekDates TABLE (WkStart DateTime, WkEnd DateTime)
WITH ENCRYPTION AS
BEGIN


	DECLARE @wkFrom datetime
	SET @wkFrom=@dateFrom
	set @wkFrom =CAST(CAST(FLOOR(CAST(@wkFrom  AS Float)) AS INT) AS DateTime)
	DECLARE @dayOfWeek int
	set @dayOfWeek=datepart(dw, @wkFrom) 	set @dayOfWeek=@dayOfWeek+6 	set @dayOfWeek=@dayOfWeek % 7 
	set @wkFrom = DateAdd(day, -1 * @dayOfWeek, @wkFrom )

	INSERT INTO @WeekDates(WkStart, WkEnd)
	(
		select dateadd(day,-((n+1)*7),@wkFrom)  AS WkStart,dateadd(day,-(n*7),@wkFrom) AS WkEnd from dbo.Utils_GetIntList(0,52)
	)

	RETURN

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ChartProcessUsage]'
GO
CREATE PROCEDURE [dbo].[Report_ChartProcessUsage] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

		SELECT NULL

		SELECT NULL

	SELECT     Utils_DateWeekBlocksOverLastYear_1.WkStart, COUNT(DISTINCT ReposProcessAccess.ProcessId) AS AccessCount
FROM         (SELECT     ProcessDefinition_Access_1.ProcessAccessId, ProcessDefinition_Access_1.ProcessId, ProcessDefinition_Access_1.DateAccessed
                            FROM          ProcessDefinition_Process AS ProcessDefinition_Process_1 INNER JOIN
                                                   ProcessDefinition_Access AS ProcessDefinition_Access_1 ON ProcessDefinition_Process_1.ProcessId = ProcessDefinition_Access_1.ProcessId
                            WHERE      (ProcessDefinition_Process_1.ForeignId = @RepositoryId)) AS ReposProcessAccess RIGHT OUTER JOIN
                      dbo.Utils_DateWeekBlocksOverLastYear(GETUTCDATE()) AS Utils_DateWeekBlocksOverLastYear_1 ON 
                      ReposProcessAccess.DateAccessed > Utils_DateWeekBlocksOverLastYear_1.WkStart AND 
                      ReposProcessAccess.DateAccessed <= Utils_DateWeekBlocksOverLastYear_1.WkEnd
                          
GROUP BY Utils_DateWeekBlocksOverLastYear_1.WkStart, Utils_DateWeekBlocksOverLastYear_1.WkEnd

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProjectPlanProjectTask]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProjectPlanProjectTask]
(
	@TaskName nvarchar(256),
	@ParentTaskId int,
	@TaskGuid nvarchar(50),
	@TaskProcessId int,
	@TaskStepId int,
	@TaskOptional bit,
	@TaskIterative bit,
	@TaskConcurrent bit,
	@TaskIsRemoved bit,
	@TaskBasedOnGuid nvarchar(50),
	@projectPlanId int,
	@TaskNotes nvarchar(max),
	@TaskPosition int,
	@TaskType int,
	@processHistoryId int,
	@RemovalReason nvarchar(max),
	@userId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	INSERT INTO ProcessDefinition_ProjectPlanTask
						  (TaskName, ParentTaskId, TaskGuid, TaskProcessId, TaskStepId, TaskOptional, TaskIterative, TaskConcurrent, TaskIsRemoved, TaskBasedOnGuid, ProjectPlanId, 
						  TaskNotes, TaskPosition, TaskType, ProcessHistoryId, RemovalReason, EditorUserId)
	VALUES     (@TaskName,@ParentTaskId,@TaskGuid,@TaskProcessId,@TaskStepId,@TaskOptional,@TaskIterative,@TaskConcurrent,@TaskIsRemoved,@TaskBasedOnGuid,@projectPlanId,
						   ISNULL(@TaskNotes, ''),@TaskPosition,@TaskType,@processHistoryId,@RemovalReason,@userId) 
     DECLARE @newId int
     SET @newId = Scope_Identity()

		INSERT INTO ProcessDefinition_ProjectPlanTaskLink(TaskId, LinksToProcessHistoryId, LinksToProcessId, ProcessLinkHistoryId)
	SELECT     @newId, ProcessDefinition_ProjectProcessVersion.ProcessHistoryId,
	ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
	FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
						  ProcessDefinition_ProjectProcessVersion ON ProcessDefinition_ProcessLinkHistory.LinksToProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId
	WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @processHistoryId) AND (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)



     RETURN @newId
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlans]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlans] 
	@repositoryName nvarchar(256),
	@projectId int,
	@maxReturn int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @filterUserId INT
	SET @filterUserId = NULL

	SELECT     @filterUserId = UserId
	FROM         ProcessDefinition_ProjectMember
	WHERE UserId=@userId AND ForceFilteredView = 1 AND ProjectId = @projectId

	IF(@filterUserId IS NULL)
	BEGIN
		SELECT    TOP(@maxReturn) ProcessDefinition_ProjectPlan.ProjectPlanId, ProcessDefinition_ProjectPlan.DateCreated, ProcessDefinition_ProjectPlan.ProjectPlanName
		FROM         ProcessDefinition_ProjectPlan INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
		WHERE     (ProcessDefinition_Project.ProjectId = @projectId) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId)
		ORDER BY ProcessDefinition_ProjectPlan.DateCreated DESC
	END	
	ELSE
	BEGIN

		SELECT  DISTINCT TOP(@maxReturn)   ProcessDefinition_ProjectPlan.ProjectPlanId, ProcessDefinition_ProjectPlan.DateCreated, ProcessDefinition_ProjectPlan.ProjectPlanName
		FROM         ProcessDefinition_ProjectPlan INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId INNER JOIN
							  ProcessDefinition_ProjectPlanTaskAssignment ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_ProjectPlanTaskAssignment.ProjectId INNER JOIN
							  ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId AND 
							  ProcessDefinition_ProjectPlanTaskAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
		WHERE     (ProcessDefinition_Project.ProjectId = @projectId) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND 
							  (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @filterUserId)
		ORDER BY ProcessDefinition_ProjectPlan.DateCreated DESC
	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetDefaultLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetDefaultLicense] 
		@licenseId int 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_License SET IsDefault = 0

	UPDATE ProcessDefinition_License SET IsDefault = 1
	WHERE LicenseId=@licenseId


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetEditableProjectPlanTasks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetEditableProjectPlanTasks] 
	@projectId int,
	@projectPlanId int,
	@parentTaskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	
	SELECT     ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
						  ProcessDefinition_ProjectPlanTask.TaskGuid, ProcessDefinition_ProjectPlanTask.TaskProcessId, ProcessDefinition_ProjectPlanTask.TaskStepId, 
						  ProcessDefinition_ProjectPlanTask.TaskOptional, ProcessDefinition_ProjectPlanTask.TaskIterative, ProcessDefinition_ProjectPlanTask.TaskConcurrent, 
						  ProcessDefinition_ProjectPlanTask.TaskIsRemoved, ProcessDefinition_ProjectPlanTask.TaskBasedOnGuid, ProcessDefinition_ProjectPlanTask.ProjectPlanId, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.TaskNotes, ProcessDefinition_ProjectPlanTask.TaskPosition, 
						  ProcessDefinition_ProjectPlanTask.RemovalReason, AltGroup
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProjectPlanTask.TaskProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectId = @projectId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
						  (ISNULL(ProcessDefinition_ProjectPlanTask.ParentTaskId, 0) = ISNULL(@parentTaskId, 0))
	ORDER BY ProcessDefinition_ProjectPlanTask.TaskPosition

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlan]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlan]
	@repositoryName nvarchar(256),
	@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_ProjectPlan.ProjectPlanId, ProcessDefinition_ProjectPlan.DateCreated, ProcessDefinition_ProjectPlan.ProjectPlanName
	FROM         ProcessDefinition_ProjectPlan INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
	WHERE     (ProcessDefinition_Project.ProjectId = @projectId) AND (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND 
						  (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaggedProjectProcessListByReposName]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaggedProjectProcessListByReposName] 
	@repositoryName nvarchar(256),
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ISNULL(Notes_Tag.TagName, 'untagged') AS TagName, ISNULL(Notes_Tag.TagId, 0) AS TagId, ProcessDefinition_ProcessHistory.ProcessId, 
						  ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle
	FROM         ProcessDefinition_Repository INNER JOIN
						  ProcessDefinition_ProcessHistory ON ProcessDefinition_Repository.RepositoryId = ProcessDefinition_ProcessHistory.ForeignId INNER JOIN
						  ProcessDefinition_ProjectProcessVersion ON 
						  ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProjectProcessVersion.ProcessHistoryId LEFT OUTER JOIN
						  Notes_Tag INNER JOIN
						  Notes_AssignedTag ON Notes_Tag.TagId = Notes_AssignedTag.TagId ON ProcessDefinition_ProcessHistory.ProcessId = Notes_AssignedTag.ForeignId
	WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)
	AND ProcessDefinition_ProcessHistory.IsDeleted=0
	ORDER BY TagName, ProcessDefinition_ProcessHistory.ProcessTitle


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessTypeByName]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessTypeByName]
(
     @typeName nvarchar(128),
     @repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

     SELECT ProcessTypeId,
            ProcessTypeName, 
            ProcessTypeTemplate
            FROM ProcessDefinition_ProcessType WHERE ProcessTypeName=@typeName 
				AND RepositoryId=@RepositoryId AND IsDeleted=0

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateMetadataFieldEx]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateMetadataFieldEx]
	@foreignId int, 
	@foreignType int,
	@MetadaType nvarchar(100),
	@IsMandatory bit,
	@ScreenLabel nvarchar(100),
	@DefaultValue nvarchar(100),
	@AllowableValues nvarchar(4000),
	@CssClass nvarchar(50),
	@FormatInfo nvarchar(50),
	@ControlData nvarchar(2000),
	@UniqueId uniqueidentifier,	
	@position int,
	@metadataId int OUTPUT
	
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		INSERT INTO Metadata_MetadataField
						  (ForeignId, ForeignType, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, 
							AllowableValues, CssClass, FormatInfo, ControlData, UniqueId)
	VALUES     (@foreignId,@foreignType,@MetadaType,@IsMandatory,@position,@ScreenLabel,@DefaultValue,@AllowableValues,@CssClass,@FormatInfo,@ControlData, @UniqueId)

	SET @metadataId=Scope_Identity()


END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectMember]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectMember] 
		@userId int, 
	@projectId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	SELECT     ProjectMemberRole, ForceFilteredView
FROM         ProcessDefinition_ProjectMember
WHERE     (ProjectId = @projectId) AND (UserId = @userId)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessesForRename]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessesForRename]
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
 
	SELECT ProcessId, ProcessTitle, PrettyPostTitle, ProcessDescription
	FROM  ProcessDefinition_Process
	WHERE (ForeignId = @RepositoryId)
	ORDER BY IsDeleted, ProcessId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessByUniqueId]'
GO
 

CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessByUniqueId]
(
     @UniqueId uniqueidentifier,
	@repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	SELECT     ProcessDefinition_Process.ForeignType, ProcessDefinition_Process.ForeignId, ProcessDefinition_Process.DateCreated, 
						  ProcessDefinition_Process.ProcessDescription, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.IsPublished, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_Process.ProcessId
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Repository ON ProcessDefinition_Process.ForeignId = ProcessDefinition_Repository.RepositoryId
	WHERE     (ProcessDefinition_Process.ProcessUId = @UniqueId) AND (ProcessDefinition_Repository.RepositoryName = @repositoryName)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetCurrentApiLicense]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetCurrentApiLicense]
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

SELECT     ProcessDefinition_License.LicenseId, ValidTo, ProcessDefinition_License.Validation, 
                      ProcessDefinition_License.ValidationCode
FROM         ProcessDefinition_License
WHERE Feature = '0x150' AND ValidTo > GetDate()

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Report_ChartProcessCreation]'
GO
CREATE PROCEDURE [dbo].[Report_ChartProcessCreation] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

		SELECT NULL

		SELECT NULL

	
	SELECT     Utils_DateWeekBlocksOverLastYear_1.WkEnd, COUNT(ProcCreation.ProcessId) AS ProcessesCreated
	FROM         (SELECT     DateCreated, ProcessId
						   FROM          ProcessDefinition_Process
						   WHERE      (ForeignId = @RepositoryId)) AS ProcCreation RIGHT OUTER JOIN
						  dbo.Utils_DateWeekBlocksOverLastYear(GetUtcDate()) AS Utils_DateWeekBlocksOverLastYear_1 ON 
						  ProcCreation.DateCreated > Utils_DateWeekBlocksOverLastYear_1.WkStart AND ProcCreation.DateCreated <= Utils_DateWeekBlocksOverLastYear_1.WkEnd
	GROUP BY Utils_DateWeekBlocksOverLastYear_1.WkEnd

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanTask]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanTask] 
	@userId int,
	@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @projectId int
	SELECT     @projectId=ProcessDefinition_ProjectPlan.ProjectId
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	IF(dbo.ProcessDefinition_HasProjectAccess(@projectId,@userId)=1)
	BEGIN
SELECT     ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
                      ProcessDefinition_ProjectPlanTask.TaskGuid, ProcessDefinition_ProjectPlanTask.TaskProcessId, ProcessDefinition_ProjectPlanTask.TaskStepId, 
                      ProcessDefinition_ProjectPlanTask.TaskOptional, ProcessDefinition_ProjectPlanTask.TaskIterative, ProcessDefinition_ProjectPlanTask.TaskConcurrent, 
                      ProcessDefinition_ProjectPlanTask.TaskIsRemoved, ProcessDefinition_ProjectPlanTask.TaskBasedOnGuid, ProcessDefinition_ProjectPlanTask.ProjectPlanId, 
                      ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.TaskNotes, ProcessDefinition_ProjectPlan.ProjectId, 
                      ProcessDefinition_ProjectPlan.ProjectPlanName, ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, 
                      ProcessDefinition_ProjectPlanTask.ActualStartDate, ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, 
                      ProcessDefinition_ProjectPlanTask.StatusNotes, ProcessDefinition_ProcessHistory.IsFrozenVersion, ProcessDefinition_ProjectPlanTask.ProcessHistoryId, 
                      ProcessDefinition_ProcessHistory.AltGroup, ProcessDefinition_ProjectPlanTask.TaskPosition, ProcessDefinition_ProjectPlanTask.TaskProgressPc,
					  ProcessDefinition_ProjectPlanTask.StepUpgradeHistory
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	END


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaskProgress]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaskProgress] 
	@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProjectPlanTaskId, EstimatedStartDate, EstimatedEndDate, ActualStartDate, ActualEndDate, '  ' AS EstimatedStartDateText, '  ' AS EstimatedEndDateText, 
						  '  ' AS ActualStartDateText, '  ' AS ActualEndDateText, CurrentStatus, StatusNotes, TaskName, '  ' AS StatusText, TaskProgressPc
	FROM         ProcessDefinition_ProjectPlanTask
	WHERE     (ProjectPlanTaskId = @taskId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateProjectMember]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_CreateProjectMember] 
		@projectId int, 
	@userId int,
	@ProjectMemberRole int,
	@ForceFilteredView bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	IF(@ProjectMemberRole=3)
	BEGIN
				SET @ForceFilteredView=0
	END

    	IF EXISTS(SELECT * FROM ProcessDefinition_ProjectMember	WHERE UserId = @userId AND ProjectId = @projectId)
	BEGIN
		UPDATE ProcessDefinition_ProjectMember 
			SET ProjectMemberRole = @ProjectMemberRole, ForceFilteredView = @ForceFilteredView
			WHERE UserId = @userId AND ProjectId = @projectId
	END
	ELSE
	BEGIN
		INSERT INTO ProcessDefinition_ProjectMember	
                      (UserId, ProjectId, ProjectMemberRole,ForceFilteredView)
		VALUES     (@userId,@projectId,@ProjectMemberRole,@ForceFilteredView)
	END
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateStep]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_CreateStep] 
	@ParentProcessId int,
	@ChildProcessId int,
	@StepName nvarchar(256),
	@StepDescription nvarchar(max),
	@StepPosition int,
	@StepType int,
	@IterationDescription nvarchar(1024),
	@OptionalDescription  nvarchar(1024),
	@bpmnJson nvarchar(MAX)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @insertedTbl table( stepUid uniqueidentifier);

	INSERT INTO ProcessDefinition_Step
						  (ParentProcessId, StepName,StepDescription, ChildProcessId, StepPosition, StepType, IterationDescription, 
						  OptionalDescription, bpmnJson)
	OUTPUT INSERTED.StepUId INTO @insertedTbl
	VALUES     (@ParentProcessId,@StepName,@StepDescription,@ChildProcessId,@StepPosition,@StepType,@IterationDescription,
		@OptionalDescription, @bpmnJson)

	SELECT stepUid FROM @insertedTbl
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetDiscussionCommenters]'
GO
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetDiscussionCommenters]
(
     @foreignId int,
      @foreignType int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;  

	
	SELECT     ProcessDefinition_Discussion.DiscussionId, ProcessDefinition_Discussion.UserId, Account_User.DisplayName, 
			Account_User.MemberEmailAddress, ProcessDefinition_ProcessHistory.MinorVersion, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
                      ProcessDefinition_ProcessHistory.ProcessTitle
	FROM         ProcessDefinition_Discussion INNER JOIN
						  Account_User ON ProcessDefinition_Discussion.UserId = Account_User.UserId INNER JOIN
						  ProcessDefinition_ProcessHistory ON ProcessDefinition_Discussion.ForeignId = ProcessDefinition_ProcessHistory.ProcessHistoryId
	WHERE     (ProcessDefinition_Discussion.ForeignType = @foreignType) AND (ProcessDefinition_ProcessHistory.ProcessId = @foreignId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetTaskProgressEstimates]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetTaskProgressEstimates]
	@taskId int,
	@EstimatedStartDate dateTime,
	@EstimatedEndDate dateTime,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	EXEC dbo.ProcessDefinition_UpdateTaskEstimateNotifications @taskId, @EstimatedStartDate, @EstimatedEndDate

	UPDATE    ProcessDefinition_ProjectPlanTask
	SET              EstimatedStartDate = @EstimatedStartDate, EstimatedEndDate = @EstimatedEndDate
	WHERE     (ProjectPlanTaskId = @taskId)

		INSERT INTO ProcessDefinition_ProjectPlanTaskEvent(TaskId, EventType, EstimatedStartDate, 
		EstimatedEndDate, ProgressPc, UserId, EventDate, CurrentStatus)
	VALUES (@taskId, 1, @EstimatedStartDate, @EstimatedEndDate, NULL, @userId, GetUtcDate(), NULL)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RemoveProjectMember]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_RemoveProjectMember]
		@projectId int, 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DELETE FROM ProcessDefinition_ProjectMember WHERE UserId = @userId AND ProjectId = @projectId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcesses]
     @repositoryName nvarchar(256),
	@PostCount int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
 
	SELECT      ProcessId, DateCreated, DescriptionSnippet AS ProcessDescription, ProcessTitle, IsPublished
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId) 
	ORDER BY ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StartTaskProgress]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_StartTaskProgress]
	@taskId int,
	@EstimatedStartDate dateTime,
	@EstimatedEndDate dateTime,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	EXEC dbo.ProcessDefinition_UpdateTaskEstimateNotifications @taskId, @EstimatedStartDate, @EstimatedEndDate

	UPDATE    ProcessDefinition_ProjectPlanTask
	SET              EstimatedStartDate = @EstimatedStartDate, EstimatedEndDate = @EstimatedEndDate, CurrentStatus = 2,
				 ActualStartDate = GetUtcDate(), 
						  StartedUserId = @userId
	WHERE     (ProjectPlanTaskId = @taskId)

		EXEC dbo.ProcessDefinition_UpdateTaskNotifications @taskId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectSendTo]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectSendTo] 
		 @repositoryName nvarchar(256),
	@projectId int
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
 

	SELECT     ProcessDefinition_Member.MemberId, ProcessDefinition_Member.UserId, ProcessDefinition_Member.MemberRole, Account_User.DisplayName, 
						  Account_User.MemberEmailAddress, CAST('' AS varchar(256)) AS GravatarUrl
	FROM         ProcessDefinition_Member INNER JOIN
						  Account_User ON ProcessDefinition_Member.UserId = Account_User.UserId INNER JOIN
							  (SELECT     UserId
								FROM          ProcessDefinition_Member AS ProcessDefinition_Member_1
								WHERE      (RepositoryId = @RepositoryId) AND (MemberRole >= 3)
								UNION
								SELECT     UserId
								FROM         ProcessDefinition_ProjectMember
								WHERE     (ProjectId = @projectId)) AS derivedtbl_1 ON Account_User.UserId = derivedtbl_1.UserId
	WHERE     (ProcessDefinition_Member.RepositoryId = @RepositoryId)
	ORDER BY Account_User.MemberEmailAddress

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetTaskProgressFinishEstimates]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetTaskProgressFinishEstimates]
	@taskId int,
	@EstimatedEndDate dateTime,
	@TaskProgressPc int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	EXEC dbo.ProcessDefinition_UpdateTaskEstimateNotifications @taskId, NULL, @EstimatedEndDate

	UPDATE    ProcessDefinition_ProjectPlanTask
	SET              EstimatedEndDate = @EstimatedEndDate, TaskProgressPc =@TaskProgressPc
	WHERE     (ProjectPlanTaskId = @taskId)

		INSERT INTO ProcessDefinition_ProjectPlanTaskEvent(TaskId, EventType, EstimatedStartDate, 
		EstimatedEndDate, ProgressPc, UserId, EventDate, CurrentStatus)
	VALUES (@taskId, 2, NULL, @EstimatedEndDate, @TaskProgressPc, @userId, GetUtcDate(), NULL)
	
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanRoot]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanRoot]
	@repositoryName nvarchar(256),
	@userId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT    TOP(1) ProcessDefinition_ProjectPlan.ProjectPlanId, ProcessDefinition_ProjectPlan.DateCreated, ProcessDefinition_ProjectPlan.ProjectPlanName, 
						  ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_Process.PrettyPostTitle, 
						  ProcessDefinition_Project.ProjectId,dbo.ProcessDefinition_HasProjectAccess(ProcessDefinition_Project.ProjectId,@userId) AS HasAccess
	FROM         ProcessDefinition_ProjectPlan INNER JOIN
						  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId INNER JOIN
						  ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlan.ProjectPlanId = ProcessDefinition_ProjectPlanTask.ProjectPlanId INNER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProjectPlanTask.TaskProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId) AND 
						  (ProcessDefinition_ProjectPlanTask.ParentTaskId IS NULL)
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_StopTaskProgress]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_StopTaskProgress]
	@taskId int,
	@FinishStatus int,
	@StatusNotes nvarchar(max),
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE    ProcessDefinition_ProjectPlanTask
	SET              CurrentStatus = @FinishStatus, ActualEndDate = GetUtcDate(), StatusNotes = @StatusNotes, FinishedUserId = @userId
	WHERE     (ProjectPlanTaskId = @taskId)

	IF(@FinishStatus=3)
	BEGIN
		UPDATE    ProcessDefinition_ProjectPlanTask
		SET              TaskProgressPc = 100
		WHERE     (ProjectPlanTaskId = @taskId)
	END

		EXEC dbo.ProcessDefinition_UpdateTaskNotifications @taskId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_OrphanedProcessList]'
GO
CREATE PROCEDURE [dbo].[Review_OrphanedProcessList] 
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     ProcessDefinition_Process.ProcessTitle AS tf_Process, 
				ProcessDefinition_Process.PrettyPostTitle AS tf_LinkName, 
				CAST(ProcessDefinition_Process.MinorVersion as nvarchar) as n_Revision, 
				ProcessDefinition_Process.DateCreated as dtl_Created, 
				ProcessDefinition_Process.DateUpdated as dtl_Updated, 
				Account_User.DisplayName  AS dd_LastEditor, 
				Account_User.MemberEmailAddress AS tf_Email
	FROM         ProcessDefinition_Process INNER JOIN
						  Account_User ON ProcessDefinition_Process.UserId = Account_User.UserId
	WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId)
and ProcessDefinition_Process.ProcessId not in
(
SELECT     LinksToProcessId
FROM         ProcessDefinition_ProcessLink
where LinksToProcessId  is not null
)
and ProcessDefinition_Process.ProcessId  not in
(
SELECT     ChildProcessId
FROM         ProcessDefinition_Step
where ChildProcessId is not null
)
AND ProcessDefinition_Process.IsDeleted=0
	ORDER BY ProcessDefinition_Process.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllProjectPlanTasks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAllProjectPlanTasks] 
	@projectId int,
	@projectPlanId int,
	@parentTaskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
						  ProcessDefinition_ProjectPlanTask.TaskGuid, ProcessDefinition_ProjectPlanTask.TaskProcessId, ProcessDefinition_ProjectPlanTask.TaskStepId, 
						  ProcessDefinition_ProjectPlanTask.TaskOptional, ProcessDefinition_ProjectPlanTask.TaskIterative, ProcessDefinition_ProjectPlanTask.TaskConcurrent, 
						  ProcessDefinition_ProjectPlanTask.TaskIsRemoved, ProcessDefinition_ProjectPlanTask.TaskBasedOnGuid, ProcessDefinition_ProjectPlanTask.ProjectPlanId, 
						  ProcessDefinition_Process.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.TaskNotes,ProcessDefinition_ProjectPlanTask.TaskPosition
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId LEFT OUTER JOIN
						  ProcessDefinition_Process ON ProcessDefinition_ProjectPlanTask.TaskProcessId = ProcessDefinition_Process.ProcessId
	WHERE     (ProcessDefinition_ProjectPlan.ProjectId = @projectId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
						  (ISNULL(ProcessDefinition_ProjectPlanTask.ParentTaskId, 0) = ISNULL(@parentTaskId, 0)) AND (ProcessDefinition_ProjectPlanTask.TaskIsRemoved = 0)
	ORDER BY ProcessDefinition_ProjectPlanTask.TaskPosition

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepository]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepository] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     RepositoryId
	FROM         ProcessDefinition_Repository
	WHERE     (RepositoryName = @repositoryName)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetTaskProgressStatus]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetTaskProgressStatus]
	@taskId int,
	@CurrentStatus int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	IF(@CurrentStatus=1)
	BEGIN
		UPDATE    ProcessDefinition_ProjectPlanTask
		SET              TaskProgressPc = 0,CurrentStatus = @CurrentStatus,FinishedUserId=NULL,StartedUserId=NULL
		WHERE     (ProjectPlanTaskId = @taskId)		
	END
	ELSE
	IF(@CurrentStatus=2)
	BEGIN
		UPDATE    ProcessDefinition_ProjectPlanTask
		SET              TaskProgressPc = 0,CurrentStatus = @CurrentStatus,FinishedUserId=NULL
		WHERE     (ProjectPlanTaskId = @taskId)		
	END
	ELSE
	IF(@CurrentStatus=3)
	BEGIN
		UPDATE    ProcessDefinition_ProjectPlanTask
		SET              CurrentStatus = @CurrentStatus,FinishedUserId=@userId
		WHERE     (ProjectPlanTaskId = @taskId)		
	END
	ELSE
	IF(@CurrentStatus=4)
	BEGIN
		UPDATE    ProcessDefinition_ProjectPlanTask
		SET              CurrentStatus = @CurrentStatus,FinishedUserId=@userId
		WHERE     (ProjectPlanTaskId = @taskId)		
	END

		INSERT INTO ProcessDefinition_ProjectPlanTaskEvent(TaskId, EventType, EstimatedStartDate, 
		EstimatedEndDate, ProgressPc, UserId, EventDate, CurrentStatus)
	VALUES (@taskId, 3, NULL, NULL, NULL, @userId, GetUtcDate(), @CurrentStatus)

		EXEC dbo.ProcessDefinition_UpdateTaskNotifications @taskId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_IsAnyAdmin]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_IsAnyAdmin] 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SELECT     @RepositoryId=RepositoryId
	FROM         ProcessDefinition_Member
	WHERE     (MemberRole = 4) AND (UserId = @userId)

	DECLARE @IsAdmin bit
	SET @IsAdmin=0
	IF(@RepositoryId IS NOT NULL)
	BEGIN
		SET @IsAdmin=1
	END

	SELECT @IsAdmin AS IsAdmin

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_CopyFromType]'
GO
CREATE PROCEDURE [dbo].[Metadata_CopyFromType] 
		@fromTypeId int , 
	@fromForeignId int,
	@toTypeId int ,
	@toForeignId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		DELETE FROM Metadata_MetadataField
	WHERE (Metadata_MetadataField.ForeignType = @toTypeId) AND (Metadata_MetadataField.ForeignId = @toForeignId)

		INSERT INTO dbo.Metadata_MetadataField(
		ForeignId, ForeignType, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, 
		CssClass, FormatInfo, ControlData, IsDeleted, UniqueId
	)
	SELECT     @toForeignId, @toTypeId, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, CssClass, 
		FormatInfo, ControlData, IsDeleted, UniqueId
	FROM        Metadata_MetadataField 
	WHERE     (Metadata_MetadataField.ForeignType = @fromTypeId) AND (Metadata_MetadataField.ForeignId = @fromForeignId) AND (IsDeleted=0)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_CreateDataHistoryChangeset]'
GO
CREATE PROCEDURE [dbo].[Metadata_CreateDataHistoryChangeset] 
	@metadataDataHistoryChangesetId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	INSERT INTO Metadata_DataHistoryChangeset
                      (ChangesetDateTime)
		VALUES     (GetUtcDate())

	SET @metadataDataHistoryChangesetId=Scope_Identity()
	

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_LinksToWrongType]'
GO
CREATE PROCEDURE [dbo].[Review_LinksToWrongType] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT ProcessFrom.ProcessTitle AS Process, ProcessDefinition_ProcessLink.SectionName AS Section, 
	ProcessDefinition_ProcessLink.LinkText AS Link, '~/' + ProcessFrom.PrettyPostTitle AS link_Link, 
	LinkType.ProcessTypeName AS SectionLinkType, LinksToProcessType.ProcessTypeName  AS LinksToType
	FROM  ProcessDefinition_ProcessLink INNER JOIN
			 ProcessDefinition_Process AS ProcessTo ON ProcessDefinition_ProcessLink.LinksToProcessId = ProcessTo.ProcessId INNER JOIN
			 ProcessDefinition_Process AS ProcessFrom ON ProcessDefinition_ProcessLink.ProcessId = ProcessFrom.ProcessId INNER JOIN
			 ProcessDefinition_ProcessType AS LinkType ON ProcessDefinition_ProcessLink.SectionLinkTypeId = LinkType.ProcessTypeId INNER JOIN
			 ProcessDefinition_ProcessType AS LinksToProcessType ON ProcessTo.ProcessTypeId = LinksToProcessType.ProcessTypeId
	WHERE (LinkType.ProcessTypeName != LinksToProcessType.ProcessTypeName) AND (ProcessTo.ForeignId = @RepositoryId)
	ORDER BY ProcessFrom.ProcessTitle,ProcessDefinition_ProcessLink.SectionName


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetStepsSvg]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_SetStepsSvg] 
	@processId int,
	@stepsSvg nvarchar(MAX)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_Process 
	SET StepsSvg = @stepsSvg 
	WHERE ProcessId = @processId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ClearProcessLinks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_ClearProcessLinks] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DELETE FROM ProcessDefinition_ProcessLink
	WHERE     (ProcessId = @processId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetStepsSvg]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetStepsSvg] 
	@processId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT  StepsSvg  FROM 
	ProcessDefinition_Process 
	WHERE ProcessId = @processId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreatePublish]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreatePublish]
(
     @RepositoryId int,
      @Title nvarchar(128),
      @Description ntext,
      @Version nvarchar(128),
      
      @userId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO ProcessDefinition_Publish
      (
            RepositoryId, 
            Title, 
            Description, 
            Version, 
            PublishDate, 
            UserId
      ) VALUES (
            @RepositoryId, 
            @Title, 
            @Description, 
            @Version, 
            GetUtcDate(), 
            @userId
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()

        INSERT INTO Notes_PublishedTag
		   (PublishId, TagId, TagName, ForeignId, ForeignType)
    SELECT @newId, Notes_Tag.TagId, Notes_Tag.TagName, Notes_Tag.ForeignId, Notes_Tag.ForeignType
    FROM  Notes_Tag INNER JOIN
		   ProcessDefinition_Process ON Notes_Tag.ForeignId = ProcessDefinition_Process.ProcessId
    WHERE (Notes_Tag.ForeignType = 144021) AND (ProcessDefinition_Process.ForeignId = @RepositoryId) AND (ProcessDefinition_Process.ForeignType = 7)

     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetAllRepositories]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAllRepositories] 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     RepositoryName, RepositoryId
FROM         ProcessDefinition_Repository

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectPlanTaskLink]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectPlanTaskLink]
(
     @TaskId int,
      @SectionName nvarchar(256),
      @LinkToProcessId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

    DECLARE @TaskLinkId int
	SELECT  @TaskLinkId=   ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId
FROM         ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
WHERE     (ProcessDefinition_ProjectPlanTaskLink.TaskId = @TaskId) AND (ProcessDefinition_ProjectPlanTaskLink.LinksToProcessId = @LinkToProcessId)
            AND SectionName = @SectionName 

     RETURN @TaskLinkId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AddProcessLink]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_AddProcessLink]
	@processId int,
	@sectionName nvarchar(256),
	@linkUri nvarchar(1024),
	@fullLinkUri nvarchar(1024),
	@linksToProcessId int,
	@linkText nvarchar(1024),
	@linkType int,
	@linkUid nvarchar(50),
	@sectionDirection nvarchar(10),
	@sectionMultiplicity nvarchar(10),
	@sectionType nvarchar(128),
	@sectionLinkTypeId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

			DECLARE @excludedProcessId int
	SET @excludedProcessId = NULL
	IF((@linkType & 1) > 0)
	BEGIN
		SET @excludedProcessId = @linksToProcessId
		SET @linksToProcessId = NULL		
	END

	INSERT INTO ProcessDefinition_ProcessLink
		(ProcessId, SectionName, LinkUri, LinksToProcessId, FullLinkUri, 
		LinkText, LinkType, LinkUid, SectionDirection, SectionMultiplicity, SectionType, SectionLinkTypeId, ExcludedLinksToProcessId)
	VALUES     (@processId,@sectionName,@linkUri,@linksToProcessId,@fullLinkUri,
		@linkText, @linkType, @linkUid, @sectionDirection, @sectionMultiplicity, @sectionType, @sectionLinkTypeId, @excludedProcessId)


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetMetadata]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetMetadata] 
	@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     MetadataId, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, ControlData, UniqueId
	FROM         Metadata_MetadataField
	WHERE     (ForeignId = @foreignId) AND (ForeignType = @foreignType) AND (IsDeleted <> 1)
	ORDER BY Position

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetFrozenProcessByName]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetFrozenProcessByName]
(
     @PostName nvarchar(256),
	@repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
SELECT     ProcessDefinition_ProcessHistory.ForeignType, ProcessDefinition_ProcessHistory.ForeignId, ProcessDefinition_ProcessHistory.DateCreated, 
                      ProcessDefinition_ProcessHistory.ProcessDescription, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.IsPublished, 
                      ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.ProcessTypeId, ProcessDefinition_ProcessType.ProcessTypeName, 
                      ProcessDefinition_ProcessHistory.DateFrozen, ProcessDefinition_ProcessHistory.ProcessHistoryId, ProcessDefinition_ProcessHistory.ProcessId,
						AltGroup
FROM         ProcessDefinition_ProcessHistory INNER JOIN
                      ProcessDefinition_ProcessType ON ProcessDefinition_ProcessHistory.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId INNER JOIN
                      ProcessDefinition_Repository ON ProcessDefinition_ProcessHistory.ForeignId = ProcessDefinition_Repository.RepositoryId
WHERE     (ProcessDefinition_ProcessHistory.IsFrozenVersion = 1) AND (ProcessDefinition_ProcessHistory.PrettyPostTitle = @PostName) AND 
                      (ProcessDefinition_Repository.RepositoryName = @repositoryName)



END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreatePublishProcess]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_CreatePublishProcess]
(
     @processId int,
      @processHistoryId int,
      @PublishId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO ProcessDefinition_PublishProcess
      (
            ProcessId, 
            ProcessHistoryId, 
            PublishId
      ) VALUES (
            @processId, 
            @processHistoryId, 
            @PublishId
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()

    INSERT INTO Notes_PublishedAssignedTag
         (PublishId, AssignedTagId, TagId, ForeignId, ForeignType, AssignedByForeignId, AssignedByForeignType, AssignedDt)
    SELECT @PublishId,AssignedTagId, TagId, ForeignId, ForeignType, AssignedByForeignId, AssignedByForeignType, AssignedDt
    FROM  Notes_AssignedTag
    WHERE (ForeignType = 144021) AND (ForeignId = @processId)

     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeletePublish]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_DeletePublish]
(
      @PublishId int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     DELETE FROM ProcessDefinition_PublishProcess
		WHERE PublishId = @PublishId

     DELETE FROM ProcessDefinition_Publish
		WHERE PublishId = @PublishId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUnremovedTasks]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_GetUnremovedTasks] 
(	
	@projectPlanId int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(

WITH UnRemovedTasks (ParentTaskId, ProjectPlanTaskId)
AS
(

	SELECT     ParentTaskId, ProjectPlanTaskId
	FROM         ProcessDefinition_ProjectPlanTask
	WHERE     (ProjectPlanId = @projectPlanId) AND (ParentTaskId IS NULL) AND (TaskIsRemoved = 0)

    UNION ALL

	SELECT     ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
	FROM         ProcessDefinition_ProjectPlanTask
		INNER JOIN UnRemovedTasks ON UnRemovedTasks.ProjectPlanTaskId=ProcessDefinition_ProjectPlanTask.ParentTaskId
	WHERE     (ProjectPlanId = @projectPlanId) AND (TaskIsRemoved = 0)
)

SELECT ParentTaskId, ProjectPlanTaskId FROM UnRemovedTasks


)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMyDocsLinks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMyDocsLinks] 

	@projectPlanId int,
	@userId int

WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
SELECT    ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, 
                      ProcessDefinition_ProjectPlanTask.ActualStartDate, ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, 
                      ProcessDefinition_ProjectPlanTask.StatusNotes, ProcessDefinition_ProjectPlanTask.TaskProgressPc, ProcessDefinition_ProcessHistory.ProcessTitle, 
                      ProcessDefinition_ProcessHistory.DescriptionSnippet, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, 
                      ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinkUri, ProcessDefinition_ProcessLinkHistory.FullLinkUri, 
                      ProcessDefinition_ProcessLinkHistory.LinkText, ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.TaskProcessId
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlanTaskAssignment ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessHistoryId
WHERE   (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId) AND 
		(ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
        (ProcessDefinition_ProjectPlanTask.CurrentStatus <= 2) AND 
		(ProcessDefinition_ProcessLinkHistory.LinksToProcessId IS NULL) AND 
		((ProcessDefinition_ProcessLinkHistory.LinkType & 1 ) = 0) AND 		( (LinkUri IS NULL) OR  NOT( (LinkUri LIKE '%PNG') OR (LinkUri LIKE '%JPG') OR (LinkUri LIKE '%GIF') OR (LinkUri LIKE '%BMP')))
ORDER BY LinkText, FullLinkUri, SectionName

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetPublishedVersions]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetPublishedVersions] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)


SELECT     PublishId, Title, [Description], Version, PublishDate
FROM         ProcessDefinition_Publish
WHERE RepositoryId=@RepositoryId
ORDER BY PublishDate DESC


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMyLinkedComponents]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMyLinkedComponents] 
	@projectPlanId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.CurrentStatus, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, 
                      ProcessDefinition_ProcessType.ProcessTypeName, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.ProcessHistoryId, 
                      ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
                      ProcessDefinition_ProjectPlanTask.TaskProcessId, ProcessDefinition_ProcessLinkHistory.SectionName
FROM         ProcessDefinition_ProjectProcessVersion INNER JOIN
                      ProcessDefinition_ProcessLinkHistory ON ProcessDefinition_ProjectProcessVersion.ProcessId = ProcessDefinition_ProcessLinkHistory.LinksToProcessId INNER JOIN
                      ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlanTaskAssignment ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId ON 
                      ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = ProcessDefinition_ProjectPlanTask.ProcessHistoryId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
                      ProcessDefinition_ProcessType ON ProcessDefinition_ProcessHistory.ProcessTypeId = ProcessDefinition_ProcessType.ProcessTypeId
WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
                      (ProcessDefinition_ProjectPlanTask.CurrentStatus <= 2) AND (ProcessDefinition_ProcessLinkHistory.LinksToProcessId IS NOT NULL) AND 
                      (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId)
ORDER BY ProcessDefinition_ProcessType.ProcessTypeName, ProcessDefinition_ProcessHistory.ProcessTitle

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_LinksToDeleted]'
GO
CREATE PROCEDURE [dbo].[Review_LinksToDeleted] 
		@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT   ProcessFrom.ProcessTitle AS Process, ProcessDefinition_ProcessLink.SectionName  AS Section, ProcessDefinition_ProcessLink.LinkText AS Link,
				ProcessDefinition_ProcessLink.FullLinkUri AS DeletedUrl,
				'~/' + ProcessFrom.PrettyPostTitle AS link_Link
	FROM         ProcessDefinition_ProcessLink INNER JOIN
						  ProcessDefinition_Process AS ProcessTo ON ProcessDefinition_ProcessLink.LinksToProcessId = ProcessTo.ProcessId INNER JOIN
						  ProcessDefinition_Process AS ProcessFrom ON ProcessDefinition_ProcessLink.ProcessId = ProcessFrom.ProcessId
	WHERE     (ProcessTo.IsDeleted = 1) AND ProcessTo.ForeignId = @RepositoryId


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetMetadataData]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetMetadataData]
	@metadataForeignId int,
	@metadataForeignType int,
	@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     Metadata_MetadataField.MetadataId, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
                      Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
                      Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, MetadataData.MetadataDataId, MetadataData.StringValue, MetadataData.IntValue, 
                      MetadataData.BoolValue, MetadataData.DoubleValue,MetadataData.DateValue, MetadataData.DateChanged, MetadataData.ChangedByUserId
FROM         Metadata_MetadataField LEFT OUTER JOIN
                          (SELECT     MetadataDataId, MetadataId, StringValue, IntValue, BoolValue, DoubleValue, DateValue, DateChanged, ChangedByUserId
                            FROM          Metadata_Data
                            WHERE      (ForeignId = @foreignId) AND (ForeignType = @foreignType)) AS MetadataData ON 
                      Metadata_MetadataField.MetadataId = MetadataData.MetadataId
WHERE     (Metadata_MetadataField.ForeignId = @metadataForeignId) AND (Metadata_MetadataField.ForeignType = @metadataForeignType) AND (Metadata_MetadataField.IsDeleted <>1)
ORDER BY Metadata_MetadataField.Position

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetHistoryStepsSvg]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_GetHistoryStepsSvg] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT  StepsSvg  FROM 
	ProcessDefinition_ProcessHistory
	WHERE ProcessHistoryId = @processHistoryId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessMap]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessMap] 
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName);

	SELECT  ProcessParent.ProcessId, ProcessParent.ProcessTitle, 
			ProcessParent.PrettyPostTitle, ProcessChild.ProcessId AS ChildProcessId, 
			ProcessChild.ProcessTitle AS ChildProcesTitle, 
			ProcessChild.PrettyPostTitle AS ChildPrettyPostTitle, 
			ProcessChild.ForeignId
	FROM         ProcessDefinition_ProcessHistory AS ProcessParent INNER JOIN
						  ProcessDefinition_Step ON ProcessParent.ProcessId = ProcessDefinition_Step.ParentProcessId INNER JOIN
						  (SELECT * FROM ProcessDefinition_Process WHERE ForeignId = @RepositoryId AND IsDeleted=0) AS ProcessChild ON ProcessDefinition_Step.ChildProcessId = ProcessChild.ProcessId
	WHERE     (ProcessParent.ForeignId = @RepositoryId) AND (ProcessParent.IsFrozenVersion = 1) AND
		(ProcessChild.ForeignId = @RepositoryId) AND ProcessParent.IsDeleted=0

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteProjectLibrary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteProjectLibrary] 
	@repositoryName varchar(256), 
	@projectId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

		SELECT    @projectId= ProjectId
	FROM         ProcessDefinition_Project
	WHERE ProcessDefinition_Project.RepositoryId = @RepositoryId

		IF(dbo.ProcessDefinition_HasProjectAccess(@projectId, @userId) = 1)
	BEGIN

delete from Metadata_DataHistory
where ForeignType = 14 and ForeignId in (
	select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))) 

delete from Metadata_DataHistory
where ForeignType = 15 and ForeignId in (
	select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from Metadata_DataHistoryChangeset
where MetadataDataHistoryChangesetId  not in (
	select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

delete from Metadata_DataHistoryChangeset
where MetadataDataHistoryChangesetId  not in (
	select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

delete from Metadata_Data
where ForeignType = 14 and ForeignId in (
	select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))) 

delete from Metadata_Data
where ForeignType = 15 and ForeignId in (
	select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from ProcessDefinition_NotificationEvent
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))


delete from ProcessDefinition_NotificationLog
where NotificationEventId NOT IN (SELECT NotificationEventId FROM ProcessDefinition_NotificationEvent)

delete from ProcessDefinition_ProjectPlanRoleAssignment
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from ProcessDefinition_ProjectPlanTaskAssignment
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from ProcessDefinition_ProjectPlanTaskEvent
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from ProcessDefinition_ProjectPlanTaskLinkHistory
where ProjectPlanTaskLinkId in ( 
	select ProjectPlanTaskLinkId from ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId)))

delete from ProcessDefinition_ProjectPlanTaskLink
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from  ProcessDefinition_ProjectPlanTaskUpgrade
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId))

delete from  ProcessDefinition_ProjectProcessType
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId)

delete from  ProcessDefinition_ProjectProcessVersion
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId)

delete from ProcessDefinition_ProjectPlanTask 
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId)

delete from ProcessDefinition_ProjectPlan
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId = @projectId)

delete from ProcessDefinition_Metric
where ProjectId = @projectId

delete from ProcessDefinition_ProjectMemberRole
where ProjectId = @projectId

delete from ProcessDefinition_ProjectMember
where ProjectId = @projectId

delete from ProcessDefinition_Project
where ProjectId = @projectId


	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetMetadataDataHistory]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetMetadataDataHistory]
	@metadataForeignId int,
	@metadataForeignType int,
	@foreignId int,
	@foreignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Metadata_MetadataField.MetadataId, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
						  Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
						  Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, MetadataData.MetadataDataId, MetadataData.StringValue, MetadataData.IntValue, 
						  MetadataData.BoolValue, MetadataData.DoubleValue, MetadataData.DateValue, MetadataData.MetadataDataHistoryChangesetId, 
						  MetadataData.ChangesetDateTime
	FROM         Metadata_MetadataField INNER JOIN
							  (SELECT     Metadata_DataHistory.MetadataDataId, Metadata_DataHistory.MetadataId, Metadata_DataHistory.StringValue, Metadata_DataHistory.IntValue, 
													   Metadata_DataHistory.BoolValue, Metadata_DataHistory.DoubleValue, Metadata_DataHistory.DateValue, 
													   Metadata_DataHistoryChangeset.MetadataDataHistoryChangesetId, Metadata_DataHistoryChangeset.ChangesetDateTime
								FROM          Metadata_DataHistory INNER JOIN
													   Metadata_DataHistoryChangeset ON 
													   Metadata_DataHistory.MetadataDataHistoryChangesetId = Metadata_DataHistoryChangeset.MetadataDataHistoryChangesetId
								WHERE      (Metadata_DataHistory.ForeignId = @foreignId) AND (Metadata_DataHistory.ForeignType = @foreignType)) AS MetadataData ON 
						  Metadata_MetadataField.MetadataId = MetadataData.MetadataId
	WHERE     (Metadata_MetadataField.ForeignId = @metadataForeignId) AND (Metadata_MetadataField.ForeignType = @metadataForeignType)
	UNION
	SELECT     Metadata_MetadataField.MetadataId, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
						  Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
						  Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, MetadataData.MetadataDataId, MetadataData.StringValue, MetadataData.IntValue, 
						  MetadataData.BoolValue, MetadataData.DoubleValue, MetadataData.DateValue, MetadataData.MetadataDataHistoryChangesetId, 
						  MetadataData.ChangesetDateTime
	FROM         Metadata_MetadataField INNER JOIN
							  (SELECT     Metadata_DataHistory.MetadataDataId, Metadata_DataHistory.MetadataId, Metadata_DataHistory.StringValue, Metadata_DataHistory.IntValue, 
													   Metadata_DataHistory.BoolValue, Metadata_DataHistory.DoubleValue, Metadata_DataHistory.DateValue, 
													   Metadata_DataHistoryChangeset.MetadataDataHistoryChangesetId, Metadata_DataHistoryChangeset.ChangesetDateTime
								FROM          Metadata_DataHistory INNER JOIN
													   Metadata_DataHistoryChangeset ON 
													   Metadata_DataHistory.MetadataDataHistoryChangesetId = Metadata_DataHistoryChangeset.MetadataDataHistoryChangesetId
								WHERE      (Metadata_DataHistory.ForeignId = @foreignId) AND (Metadata_DataHistory.ForeignType = @foreignType)) AS MetadataData ON 
						  Metadata_MetadataField.MetadataId = MetadataData.MetadataId
	WHERE     (Metadata_MetadataField.ForeignId = @metadataForeignId) AND ((Metadata_MetadataField.ForeignType = 18) AND @metadataForeignType=16) 
	ORDER BY MetadataData.MetadataDataHistoryChangesetId DESC, Metadata_MetadataField.Position
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRaisedNotifications]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRaisedNotifications] 
		@projectPlanId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


SELECT     ProcessDefinition_NotificationLog.DateSent, ProcessDefinition_NotificationEvent.EventId, ProcessDefinition_NotificationEvent.TaskId, 
                      CASE ProcessDefinition_NotificationEvent.EventId WHEN 1 THEN 'Estimated start approaching' WHEN 2 THEN 'Estimated finish appraoching' WHEN 3 THEN 'Task is ready to start'
                       END AS EventLabel, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.TaskProcessId, 
                      ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.ProjectPlanId
FROM         ProcessDefinition_NotificationLog INNER JOIN
                      ProcessDefinition_NotificationEvent ON 
                      ProcessDefinition_NotificationLog.NotificationEventId = ProcessDefinition_NotificationEvent.NotificationEventId LEFT OUTER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_NotificationEvent.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
WHERE     (ProcessDefinition_NotificationLog.UserId = @userId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId)
ORDER BY ProcessDefinition_NotificationLog.DateSent DESC

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpgradeTask]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpgradeTask] 
	@userId int,
	@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @projectId int
	DECLARE @processId int
	DECLARE @oldProcessHistoryId int
	SELECT     @projectId=ProcessDefinition_ProjectPlan.ProjectId, @processId=TaskProcessId, @oldProcessHistoryId = ProcessHistoryId
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	IF(dbo.ProcessDefinition_HasProjectAccess(@projectId,@userId)=1 AND NOT(@processId IS NULL))
	BEGIN
				DECLARE @RepositoryId int
		SELECT     @RepositoryId=ProcessDefinition_Project.RepositoryId
		FROM         ProcessDefinition_ProjectPlan INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_ProjectPlan.ProjectId = ProcessDefinition_Project.ProjectId
		WHERE     (ProcessDefinition_ProjectPlan.ProjectId = @projectId)

				DECLARE @newProcessHistoryId int
		SELECT @newProcessHistoryId = ProcessHistoryId 
		FROM ProcessDefinition_ProcessHistory
	    WHERE  (ForeignType = 7) AND (ForeignId = @RepositoryId) AND IsFrozenVersion=1 AND ProcessId=@processId

				INSERT INTO ProcessDefinition_ProjectPlanTaskUpgrade(TaskId, UserId, DateUpgraded, OldProcessHistoryId, NewProcessHsitoryId)
		VALUES(@taskId, @userId, GetUtcDate(), @oldProcessHistoryId, @newProcessHistoryId)
		DECLARE @taskUpgradeId int
		SET @taskUpgradeId=Scope_Identity()

		INSERT INTO ProcessDefinition_ProjectPlanTaskLinkHistory(TaskUpgradeId, ProjectPlanTaskLinkId, LinksToProcessHistoryId, LinksToProcessId, ProcessLinkHistoryId)
		SELECT     @taskUpgradeId, ProjectPlanTaskLinkId, LinksToProcessHistoryId, LinksToProcessId, ProcessLinkHistoryId
		FROM         ProcessDefinition_ProjectPlanTaskLink
		WHERE     (TaskId = @taskId)
		
				UPDATE ProcessDefinition_ProjectPlanTask
		SET ProcessHistoryId = @newProcessHistoryId 
		WHERE ProjectPlanTaskId = @taskId

				DELETE FROM ProcessDefinition_ProjectPlanTaskLink
		WHERE TaskId = @taskId

				INSERT INTO ProcessDefinition_ProjectPlanTaskLink(TaskId, LinksToProcessHistoryId, LinksToProcessId, ProcessLinkHistoryId)
		SELECT     @taskId, LinksToProcessHistory.ProcessHistoryId, ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
		FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
							  ProcessDefinition_ProcessHistory AS LinksToProcessHistory ON 
							  ProcessDefinition_ProcessLinkHistory.LinksToProcessId = LinksToProcessHistory.ProcessId
		WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @newProcessHistoryId) AND (LinksToProcessHistory.IsFrozenVersion = 1)	


UPDATE Metadata_DataHistory
SET MetadataId = x.NewMetadataId
FROM (
SELECT     Metadata_Data.MetadataId AS OldMetadataId, NewMetadataId.MetadataId AS NewMetadataId
FROM         Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                          (SELECT     MetadataId, UniqueId
                            FROM          Metadata_MetadataField AS Metadata_MetadataField_1
                            WHERE      (ForeignId = @newProcessHistoryId) AND (ForeignType = 16 OR
                                                   ForeignType = 18)) AS NewMetadataId ON Metadata_MetadataField.UniqueId = NewMetadataId.UniqueId
WHERE     (Metadata_Data.ForeignType = 15) AND (Metadata_Data.ForeignId = @taskId) AND (Metadata_MetadataField.ForeignId = @oldProcessHistoryId) AND 
                      (Metadata_MetadataField.ForeignType = 16 OR
                      Metadata_MetadataField.ForeignType = 18)) as x
WHERE Metadata_DataHistory.MetadataId=x.OldMetadataId AND Metadata_DataHistory.ForeignType = 15 AND (Metadata_DataHistory.ForeignId = @taskId)

UPDATE Metadata_Data
SET MetadataId = x.NewMetadataId
FROM (
SELECT     Metadata_Data.MetadataId AS OldMetadataId, NewMetadataId.MetadataId AS NewMetadataId
FROM         Metadata_Data INNER JOIN
                      Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                          (SELECT     MetadataId, UniqueId
                            FROM          Metadata_MetadataField AS Metadata_MetadataField_1
                            WHERE      (ForeignId = @newProcessHistoryId) AND (ForeignType = 16 OR
                                                   ForeignType = 18)) AS NewMetadataId ON Metadata_MetadataField.UniqueId = NewMetadataId.UniqueId
WHERE     (Metadata_Data.ForeignType = 15) AND (Metadata_Data.ForeignId = @taskId) AND (Metadata_MetadataField.ForeignId = @oldProcessHistoryId) AND 
                      (Metadata_MetadataField.ForeignType = 16 OR
                      Metadata_MetadataField.ForeignType = 18)) as x
WHERE Metadata_Data.MetadataId=x.OldMetadataId AND Metadata_Data.ForeignType = 15 AND (Metadata_Data.ForeignId = @taskId)




UPDATE Metadata_DataHistory
SET MetadataId = x.NewMetadataId, ForeignId=x.NewDataForeignId
FROM (
SELECT     OldData.OldMetadataId, OldData.OldDataForeignId, NewData.NewMetadataId, NewData.NewDataForeignId
FROM         (SELECT     Metadata_Data.MetadataId AS OldMetadataId, Metadata_Data.ForeignId AS OldDataForeignId, ProcessDefinition_ProcessLinkHistory.ProcessId, 
                                              ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinkUri, 
                                              ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProjectPlanTaskLinkHistory.LinksToProcessHistoryId, 
                                              Metadata_MetadataField.UniqueId,ProcessDefinition_ProcessLinkHistory.LinkUid
                       FROM          Metadata_Data INNER JOIN
                                              Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                                              ProcessDefinition_ProjectPlanTaskLinkHistory INNER JOIN
                                              ProcessDefinition_ProjectPlanTaskUpgrade ON 
                                              ProcessDefinition_ProjectPlanTaskLinkHistory.TaskUpgradeId = ProcessDefinition_ProjectPlanTaskUpgrade.TaskUpgradeId ON 
                                              Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTaskLinkHistory.ProjectPlanTaskLinkId AND 
                                              Metadata_MetadataField.ForeignId = ProcessDefinition_ProjectPlanTaskLinkHistory.LinksToProcessHistoryId INNER JOIN
                                              ProcessDefinition_ProcessLinkHistory ON 
                                              ProcessDefinition_ProjectPlanTaskLinkHistory.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
                       WHERE      (Metadata_Data.ForeignType = 14) AND (Metadata_MetadataField.ForeignType = 16 OR
                                              Metadata_MetadataField.ForeignType = 18) AND (ProcessDefinition_ProjectPlanTaskUpgrade.TaskUpgradeId = @taskUpgradeId)) AS OldData INNER JOIN
                          (SELECT     Metadata_MetadataField_1.MetadataId AS NewMetadataId, ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId AS NewDataForeignId, 
                                                   ProcessDefinition_ProcessLinkHistory_1.ProcessId, ProcessDefinition_ProcessLinkHistory_1.SectionName, 
                                                   ProcessDefinition_ProcessLinkHistory_1.LinkUri, ProcessDefinition_ProcessLinkHistory_1.LinksToProcessId, 
                                                   ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId, Metadata_MetadataField_1.UniqueId,ProcessDefinition_ProcessLinkHistory_1.LinkUid
                            FROM          ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                                                   ProcessDefinition_ProcessLinkHistory AS ProcessDefinition_ProcessLinkHistory_1 ON 
                                                   ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory_1.ProcessLinkHistoryId INNER JOIN
                                                   Metadata_MetadataField AS Metadata_MetadataField_1 ON 
                                                   ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = Metadata_MetadataField_1.ForeignId
                            WHERE      (ProcessDefinition_ProjectPlanTaskLink.TaskId = @taskId) AND (Metadata_MetadataField_1.ForeignType = 16 OR
                                                   Metadata_MetadataField_1.ForeignType = 18)) AS NewData ON OldData.ProcessId = NewData.ProcessId AND 
                      OldData.SectionName = NewData.SectionName AND OldData.LinkUri = NewData.LinkUri AND OldData.LinksToProcessId = NewData.LinksToProcessId AND 
                      OldData.UniqueId = NewData.UniqueId AND (ISNULL(OldData.LinkUid,0)=ISNULL(NewData.LinkUid,0))) AS x
WHERE Metadata_DataHistory.ForeignId = x.OldDataForeignId AND Metadata_DataHistory.MetadataId=x.OldMetadataId

UPDATE Metadata_Data
SET MetadataId = x.NewMetadataId, ForeignId=x.NewDataForeignId
FROM (
SELECT     OldData.OldMetadataId, OldData.OldDataForeignId, NewData.NewMetadataId, NewData.NewDataForeignId
FROM         (SELECT     Metadata_Data.MetadataId AS OldMetadataId, Metadata_Data.ForeignId AS OldDataForeignId, ProcessDefinition_ProcessLinkHistory.ProcessId, 
                                              ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinkUri, 
                                              ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProjectPlanTaskLinkHistory.LinksToProcessHistoryId, 
                                              Metadata_MetadataField.UniqueId,ProcessDefinition_ProcessLinkHistory.LinkUid
                       FROM          Metadata_Data INNER JOIN
                                              Metadata_MetadataField ON Metadata_Data.MetadataId = Metadata_MetadataField.MetadataId INNER JOIN
                                              ProcessDefinition_ProjectPlanTaskLinkHistory INNER JOIN
                                              ProcessDefinition_ProjectPlanTaskUpgrade ON 
                                              ProcessDefinition_ProjectPlanTaskLinkHistory.TaskUpgradeId = ProcessDefinition_ProjectPlanTaskUpgrade.TaskUpgradeId ON 
                                              Metadata_Data.ForeignId = ProcessDefinition_ProjectPlanTaskLinkHistory.ProjectPlanTaskLinkId AND 
                                              Metadata_MetadataField.ForeignId = ProcessDefinition_ProjectPlanTaskLinkHistory.LinksToProcessHistoryId INNER JOIN
                                              ProcessDefinition_ProcessLinkHistory ON 
                                              ProcessDefinition_ProjectPlanTaskLinkHistory.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId
                       WHERE      (Metadata_Data.ForeignType = 14) AND (Metadata_MetadataField.ForeignType = 16 OR
                                              Metadata_MetadataField.ForeignType = 18) AND (ProcessDefinition_ProjectPlanTaskUpgrade.TaskUpgradeId = @taskUpgradeId)) AS OldData INNER JOIN
                          (SELECT     Metadata_MetadataField_1.MetadataId AS NewMetadataId, ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId AS NewDataForeignId, 
                                                   ProcessDefinition_ProcessLinkHistory_1.ProcessId, ProcessDefinition_ProcessLinkHistory_1.SectionName, 
                                                   ProcessDefinition_ProcessLinkHistory_1.LinkUri, ProcessDefinition_ProcessLinkHistory_1.LinksToProcessId, 
                                                   ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId, Metadata_MetadataField_1.UniqueId,ProcessDefinition_ProcessLinkHistory_1.LinkUid
                            FROM          ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                                                   ProcessDefinition_ProcessLinkHistory AS ProcessDefinition_ProcessLinkHistory_1 ON 
                                                   ProcessDefinition_ProjectPlanTaskLink.ProcessLinkHistoryId = ProcessDefinition_ProcessLinkHistory_1.ProcessLinkHistoryId INNER JOIN
                                                   Metadata_MetadataField AS Metadata_MetadataField_1 ON 
                                                   ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = Metadata_MetadataField_1.ForeignId
                            WHERE      (ProcessDefinition_ProjectPlanTaskLink.TaskId = @taskId) AND (Metadata_MetadataField_1.ForeignType = 16 OR
                                                   Metadata_MetadataField_1.ForeignType = 18)) AS NewData ON OldData.ProcessId = NewData.ProcessId AND 
                      OldData.SectionName = NewData.SectionName AND OldData.LinkUri = NewData.LinkUri AND OldData.LinksToProcessId = NewData.LinksToProcessId AND 
                      OldData.UniqueId = NewData.UniqueId  AND (ISNULL(OldData.LinkUid,0)=ISNULL(NewData.LinkUid,0))) AS x
WHERE Metadata_Data.ForeignId = x.OldDataForeignId AND Metadata_Data.MetadataId=x.OldMetadataId




	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_IsUserRepositoryMember]'
GO
CREATE FUNCTION [dbo].[ProcessDefinition_IsUserRepositoryMember] 
(
		@repositoryName varchar(256),
	@userId int
)
RETURNS bit
WITH ENCRYPTION AS
BEGIN
		DECLARE @Result bit

		IF EXISTS (SELECT     ProcessDefinition_Member.MemberId
				FROM         ProcessDefinition_Member INNER JOIN
									  ProcessDefinition_Repository ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Repository.RepositoryId
				WHERE     (ProcessDefinition_Member.UserId = @userId) AND (ProcessDefinition_Repository.RepositoryName = @repositoryName))
	BEGIN
		SET @Result = 1
	END
	ELSE
	BEGIN
		SET @Result = 0
	END

		RETURN @Result

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_DeleteProcessLibrary]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_DeleteProcessLibrary] 
	@repositoryName varchar(256), 
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @delReposId int
	SET @delReposId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

		IF(dbo.ProcessDefinition_IsUserRepositoryMember(@repositoryName, @userId) = 1)
	BEGIN
	

delete from Metadata_DataHistory
where ForeignType = 14 and ForeignId in (
	select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))) 

delete from Metadata_DataHistory
where ForeignType = 15 and ForeignId in (
	select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
		SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from Metadata_DataHistoryChangeset
where MetadataDataHistoryChangesetId  not in (
	select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

delete from Metadata_DataHistoryChangeset
where MetadataDataHistoryChangesetId  not in (
	select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

delete from Metadata_Data
where ForeignType = 14 and ForeignId in (
	select  ProjectPlanTaskLinkId FROM ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))) 

delete from Metadata_Data
where ForeignType = 15 and ForeignId in (
	select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
		SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from ProcessDefinition_NotificationEvent
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from ProcessDefinition_NotificationLog
where NotificationEventId NOT IN (SELECT NotificationEventId FROM ProcessDefinition_NotificationEvent)

delete from ProcessDefinition_ProjectPlanRoleAssignment
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from ProcessDefinition_ProjectPlanTaskAssignment
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from ProcessDefinition_ProjectPlanTaskEvent
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from ProcessDefinition_ProjectPlanTaskLinkHistory
where ProjectPlanTaskLinkId in ( 
	select ProjectPlanTaskLinkId from ProcessDefinition_ProjectPlanTaskLink where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId))))

delete from ProcessDefinition_ProjectPlanTaskLink
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from  ProcessDefinition_ProjectPlanTaskUpgrade
where TaskId IN (
		select ProjectPlanTaskId from ProcessDefinition_ProjectPlanTask where ProjectPlanId IN (
			SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)))

delete from  ProcessDefinition_ProjectProcessType
where ProjectPlanId IN (
	SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId))

delete from  ProcessDefinition_ProjectProcessVersion
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId))

delete from ProcessDefinition_ProjectPlanTask 
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId))

delete from ProcessDefinition_ProjectPlan
where ProjectPlanId IN (SELECT ProjectPlanId FROM ProcessDefinition_ProjectPlan where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId))

delete from ProcessDefinition_Metric
where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)

delete from ProcessDefinition_ProjectMemberRole
where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)

delete from ProcessDefinition_ProjectMember
where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)

delete from ProcessDefinition_Project
where ProjectId IN (
				SELECT ProjectId FROM ProcessDefinition_Project where RepositoryId = @delReposId)

delete from ProcessDefinition_ActiveProject
where RepositoryId = @delReposId


delete from Metadata_DataHistory
where ForeignType = 21 and ForeignId in (
	SELECT ProcessLinkHistoryId FROM ProcessDefinition_ProcessLinkHistory WHERE ProcessId IN (
		SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId))

delete from Metadata_DataHistory
where ForeignType = 20 and ForeignId in (
	SELECT ProcessLinkDataId FROM ProcessDefinition_ProcessLinkData WHERE ProcessId IN (
		SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId))

delete from Metadata_DataHistoryChangeset
where MetadataDataHistoryChangesetId  not in (
	select MetadataDataHistoryChangesetId from dbo.Metadata_DataHistory )

delete from Metadata_Data
where ForeignType = 21 and ForeignId in (
	SELECT ProcessLinkHistoryId FROM ProcessDefinition_ProcessLinkHistory WHERE ProcessId IN (
		SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId))

delete from Metadata_Data
where ForeignType = 20 and ForeignId in (
	SELECT ProcessLinkDataId FROM ProcessDefinition_ProcessLinkData WHERE ProcessId IN (
		SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId) )

delete from Metadata_MetadataField
where (ForeignType = 7 OR ForeignType = 10) AND ForeignId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

delete from Metadata_MetadataField
where (ForeignType = 16 OR ForeignType = 18 OR ForeignType = 19) AND ForeignId IN (
	SELECT ProcessHistoryId FROM ProcessDefinition_ProcessHistory WHERE ProcessId IN (
		SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId))

delete from Metadata_MetadataField
where (ForeignType = 11 OR ForeignType = 17) AND ForeignId IN (
	SELECT ProcessTypeId FROM ProcessDefinition_ProcessType WHERE RepositoryId = @delReposId )

DELETE FROM dbo.Notes_AssignedTag
WHERE ForeignId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM Notes_Tag
where TagId NOT IN (Select TagId FROM Notes_AssignedTag)

DELETE FROM dbo.ProcessDefinition_Access
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_Discussion
WHERE ForeignId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_Member
WHERE RepositoryId = @delReposId

DELETE FROM ProcessDefinition_Metric
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_ProcessHistory
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_ProcessLink
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_ProcessLinkData
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_ProcessLinkHistory
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM dbo.ProcessDefinition_Step
WHERE ParentProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM dbo.ProcessDefinition_StepHistory
WHERE ParentProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_PublishProcess
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_Publish
WHERE RepositoryId = @delReposId

DELETE FROM ProcessDefinition_Process
WHERE ProcessId IN 
(SELECT ProcessId FROM dbo.ProcessDefinition_Process WHERE ForeignId = @delReposId)

DELETE FROM ProcessDefinition_UploadedFile
WHERE RepositoryId = @delReposId

DELETE FROM ProcessDefinition_ProcessType
WHERE RepositoryId = @delReposId

DELETE FROM ProcessDefinition_RepositorySettings
WHERE RepositoryId = @delReposId

DELETE FROM ProcessDefinition_Repository
WHERE RepositoryId = @delReposId


		

	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetIndividualMetadataData]'
GO
CREATE FUNCTION [dbo].[Metadata_GetIndividualMetadataData] 
(	
	@metadataId int, 
	@foreignType int
)
RETURNS TABLE 
WITH ENCRYPTION AS
RETURN 
(

	SELECT     StringValue, IntValue, BoolValue, DoubleValue, DateValue, ForeignId
	FROM         Metadata_Data
	WHERE     (ForeignType = @foreignType) AND (MetadataId = @metadataId)

)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_IsTaskUpgradeAvailable]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_IsTaskUpgradeAvailable] 
		@taskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	
	DECLARE @Ret bit

	DECLARE @IsTaskFrozenVersion bit
	SELECT  @IsTaskFrozenVersion =   TaskProcessHistory.IsFrozenVersion
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProcessHistory AS TaskProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = TaskProcessHistory.ProcessHistoryId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @taskId)

	IF(@IsTaskFrozenVersion = 1) 
	BEGIN
				IF(EXISTS(SELECT     ProcessDefinition_ProjectPlanTaskLink.ProjectPlanTaskLinkId
		FROM         ProcessDefinition_ProcessHistory AS LinkProcessHistory INNER JOIN
							  ProcessDefinition_ProjectPlanTaskLink ON LinkProcessHistory.ProcessHistoryId = ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId
		WHERE     (ProcessDefinition_ProjectPlanTaskLink.TaskId = @taskId) AND (LinkProcessHistory.IsFrozenVersion = 0)))
		BEGIN
						SET @Ret = 1
		END

	END
	ELSE
	BEGIN
				SET @Ret = 1
	END

RETURN @Ret

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetMetadataDataItem]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetMetadataDataItem]
	@foreignId int,
	@foreignType int,
	@metadataId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     Metadata_MetadataField.MetadataId, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
                      Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
                      Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, MetadataData.MetadataDataId, MetadataData.StringValue, MetadataData.IntValue, 
                      MetadataData.BoolValue, MetadataData.DoubleValue,MetadataData.DateValue, MetadataData.DateChanged, MetadataData.ChangedByUserId
FROM         Metadata_MetadataField LEFT OUTER JOIN
                          (SELECT     MetadataDataId, MetadataId, StringValue, IntValue, BoolValue, DoubleValue, DateValue, DateChanged, ChangedByUserId
                            FROM          Metadata_Data
                            WHERE      (ForeignId = @foreignId) AND (ForeignType = @foreignType)) AS MetadataData ON 
                      Metadata_MetadataField.MetadataId = MetadataData.MetadataId
WHERE     (Metadata_MetadataField.MetadataId = @metadataId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMyComments]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMyComments] 
		@projectPlanId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
SELECT     ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, 
                      ProcessDefinition_ProjectPlanTask.ProcessHistoryId, MyPastComments.CreatedDateTime, MyPastComments.DiscussionText, 
                      ProcessDefinition_ProjectPlanTask.TaskProcessId
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                          (SELECT     UserId, ForeignId, CreatedDateTime, DiscussionText
                            FROM          ProcessDefinition_Discussion
                            WHERE      (UserId = @userId) AND (ForeignType = 16)) AS MyPastComments ON 
                      ProcessDefinition_ProjectPlanTask.ProcessHistoryId = MyPastComments.ForeignId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId)
ORDER BY MyPastComments.CreatedDateTime DESC
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessDescription]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessDescription]
(
     @processId int,
      @ProcessDescription nvarchar(max)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	UPDATE    ProcessDefinition_Process
	SET              ProcessDescription = @ProcessDescription
	WHERE     (ProcessId = @processId)


END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_SetData]'
GO
CREATE PROCEDURE [dbo].[Metadata_SetData] 
	@metadataId int,
	@foreignId int, 
	@foreignType int,
	@StringValue nvarchar(max),
	@IntValue int,
	@BoolValue bit,
	@DoubleValue float,
	@DateValue datetime,
	@storeHistory bit,
	@metadataDataHistoryChangesetId int,
	@userId int,
	@metadataDataId int OUTPUT,
	@newMetadataDataHistoryChangesetId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @PreviousStringValue nvarchar(max),
			@PreviousIntValue int,
			@PreviousBoolValue bit,
			@PreviousDoubleValue float,
			@PreviousDateValue datetime,
			@PreviousDateChanged datetime, 
			@PreviousChangedByUserId int

	

		SELECT @metadataDataId=MetadataDataId,
			@PreviousStringValue=StringValue,
			@PreviousIntValue=IntValue,
			@PreviousBoolValue=BoolValue,
			@PreviousDoubleValue=DoubleValue,
			@PreviousDateValue=DateValue,
			@PreviousDateChanged = DateChanged, 
			@PreviousChangedByUserId = ChangedByUserId
			 FROM Metadata_Data 
	WHERE     (MetadataId = @metadataId) AND (ForeignId = @foreignId) AND (ForeignType = @foreignType)

	IF(@metadataDataId IS NOT NULL)
	BEGIN
				DECLARE @bitChanged bit
		SET @bitChanged=0
		IF(@PreviousStringValue<>@StringValue)
			SET @bitChanged=1
		IF(@PreviousIntValue<>@IntValue)
			SET @bitChanged=1
		IF(@PreviousBoolValue<>@BoolValue)
			SET @bitChanged=1
		IF(@PreviousDoubleValue<>@DoubleValue)
			SET @bitChanged=1
		IF(@PreviousDateValue<>@DateValue)
			SET @bitChanged=1

		IF(@bitChanged=1)
		BEGIN
			IF(@storeHistory=1)
			BEGIN
								IF(@metadataDataHistoryChangesetId IS NULL)
				BEGIN
					EXEC Metadata_CreateDataHistoryChangeset @metadataDataHistoryChangesetId=@metadataDataHistoryChangesetId OUTPUT
				END

								SET @newMetadataDataHistoryChangesetId=@metadataDataHistoryChangesetId

								INSERT INTO Metadata_DataHistory
									  (MetadataDataHistoryChangesetId,MetadataDataId,MetadataId, ForeignId, ForeignType, 
							StringValue, IntValue, BoolValue, DoubleValue, DateValue, DateChanged, ChangedByUserId)
				VALUES     (@metadataDataHistoryChangesetId,@metadataDataId,@metadataId,@foreignId,@foreignType,
							@PreviousStringValue,@PreviousIntValue,@PreviousBoolValue,@PreviousDoubleValue,@PreviousDateValue,
							@PreviousDateChanged, @PreviousChangedByUserId)	
			END

			UPDATE    Metadata_Data
			SET              StringValue = @StringValue, IntValue = @IntValue, BoolValue = @BoolValue, DoubleValue = @DoubleValue, DateValue = @DateValue,
				DateChanged  = GetUtcDate(), ChangedByUserId = @userId
			WHERE     (MetadataDataId = @metadataDataId)
		END
	END
	ELSE
	BEGIN
		INSERT INTO Metadata_Data
							  (MetadataId, ForeignId, ForeignType, StringValue, IntValue, BoolValue, DoubleValue, DateValue, DateChanged, ChangedByUserId)
		VALUES     (@metadataId,@foreignId,@foreignType,@StringValue,@IntValue,@BoolValue,@DoubleValue,@DateValue, GetUtcDate(), @userId)	

		SET @metadataDataId=Scope_Identity()

	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetMaxPosition]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetMaxPosition] 
	@foreignId int,
	@foreignType int,
	@position int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     @position = MAX(Position)
FROM         Metadata_MetadataField
WHERE      (ForeignId = @foreignId) AND (ForeignType = @foreignType) AND (IsDeleted<>1)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProjectRoleAssignments]'
GO


CREATE PROCEDURE [dbo].[ProcessDefinition_GetProjectRoleAssignments] 
		@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

    	DECLARE @roleTypeId int
SELECT    @roleTypeId= ProcessDefinition_RepositorySettings.PersonProcessTypeId
FROM         ProcessDefinition_Project INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectPlan.ProjectId INNER JOIN
                      ProcessDefinition_RepositorySettings ON ProcessDefinition_Project.RepositoryId = ProcessDefinition_RepositorySettings.RepositoryId
WHERE     (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)


SELECT     ProcessDefinition_ProjectPlanTask.ProjectPlanId, ProcessDefinition_ProcessHistory.ProcessTypeId, ProcessDefinition_ProcessHistory.ProcessTitle, 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId, ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ParentTaskId, 
                      ProcessDefinition_ProjectPlanTask.ProcessHistoryId, ProcessDefinition_ProjectPlanTask.TaskProcessId, 
                      ProcessDefinition_ProjectPlanTaskLink.LinksToProcessId
FROM         ProcessDefinition_ProjectPlanTaskLink INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanTaskLink.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProcessHistory ON 
                      ProcessDefinition_ProjectPlanTaskLink.LinksToProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND (ProcessDefinition_ProcessHistory.ProcessTypeId = @roleTypeId) AND 
                      (ProcessDefinition_ProjectPlanTask.TaskIsRemoved = 0)
ORDER BY ProcessDefinition_ProcessHistory.ProcessTitle,ProcessDefinition_ProjectPlanTask.TaskName

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_UpdateMetadataField]'
GO
CREATE PROCEDURE [dbo].[Metadata_UpdateMetadataField]
	@metadataId int,
	@MetadaType nvarchar(100),
	@IsMandatory bit,
	@ScreenLabel nvarchar(100),
	@DefaultValue nvarchar(100),
	@AllowableValues nvarchar(4000),
	@CssClass nvarchar(50),
	@FormatInfo nvarchar(50),
	@ControlData nvarchar(2000)	
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

UPDATE    Metadata_MetadataField
SET       MetadataType =@MetadaType, IsMandatory =@IsMandatory, ScreenLabel =@ScreenLabel, 
		DefaultValue =@DefaultValue, AllowableValues =@AllowableValues, CssClass =@CssClass, 
		FormatInfo =@FormatInfo, ControlData =@ControlData
WHERE (MetadataId = @metadataId)

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateRepositorySettings]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateRepositorySettings] 
		@repositoryName nvarchar(256),
	@PersonProcessTypeId int,
	@ProcessTypeId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    	IF EXISTS (SELECT RepositoryId FROM ProcessDefinition_RepositorySettings WHERE RepositoryId = @RepositoryId)
	BEGIN
		UPDATE ProcessDefinition_RepositorySettings 
		SET PersonProcessTypeId = @PersonProcessTypeId, ProcessTypeId = @ProcessTypeId 
		WHERE RepositoryId = @RepositoryId
	END
	ELSE
	BEGIN
		INSERT INTO ProcessDefinition_RepositorySettings (RepositoryId, PersonProcessTypeId, ProcessTypeId) 
		VALUES (@RepositoryId, @PersonProcessTypeId, @ProcessTypeId)
	END
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_DeleteMetadataField]'
GO
CREATE PROCEDURE [dbo].[Metadata_DeleteMetadataField]
	@metadataId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @foreignId int
	DECLARE @foreignType int 
	DECLARE @position int 
	SELECT @position = Position, @foreignId = ForeignId,  @foreignType = ForeignType
	FROM Metadata_MetadataField 
	WHERE MetadataId=@metadataId 

	UPDATE Metadata_MetadataField SET IsDeleted=1
	WHERE     (MetadataId = @metadataId)

		UPDATE Metadata_MetadataField SET Position=Position-1 
	WHERE Position>@position AND @foreignId = ForeignId AND  @foreignType = ForeignType AND IsDeleted<>1


END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRoleAssignments]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRoleAssignments] 
	@projectPlanId int,
	@roleId int 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     Account_User.DisplayName, ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId, ProcessDefinition_ProjectPlanRoleAssignment.AssignedToId, 
                      ProcessDefinition_ProjectPlanRoleAssignment.RoleAssignmentId, ProcessDefinition_ProjectPlanRoleAssignment.TaskId, 
                      ProcessDefinition_ProjectPlanRoleAssignment.AssignmentNote, ProcessDefinition_ProjectPlanRoleAssignment.AssignmentDate
FROM         ProcessDefinition_ProjectPlanRoleAssignment INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanRoleAssignment.AssignedToId = Account_User.UserId INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanRoleAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND (ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId = @roleId) AND 
                      (NOT (ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId IS NULL))
ORDER BY Account_User.DisplayName

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetRepositorySettings]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetRepositorySettings]
	 @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    SELECT     ProcessDefinition_RepositorySettings.PersonProcessTypeId, 
		(SELECT ProcessTypeName FROM ProcessDefinition_ProcessType WHERE ProcessTypeId = ProcessDefinition_RepositorySettings.PersonProcessTypeId) AS PersonProcessTypeName,
		ProcessDefinition_RepositorySettings.ProcessTypeId, 		
		(SELECT ProcessTypeName FROM ProcessDefinition_ProcessType WHERE ProcessTypeId = ProcessDefinition_RepositorySettings.ProcessTypeId) AS ProcessTypeName
FROM         ProcessDefinition_RepositorySettings 
WHERE     (ProcessDefinition_RepositorySettings.RepositoryId = @RepositoryId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_MoveDownMetadataField]'
GO
CREATE PROCEDURE [dbo].[Metadata_MoveDownMetadataField]
	@metadataId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @foreignId int
	DECLARE @foreignType int 
	DECLARE @position int 
	SELECT @position = Position, @foreignId = ForeignId,  @foreignType = ForeignType
	FROM Metadata_MetadataField 
	WHERE MetadataId=@metadataId 

	DECLARE @MaxPos int 
	SELECT @MaxPos=MAX(Position) 
	FROM Metadata_MetadataField 
	WHERE ForeignId = @foreignId AND ForeignType = @foreignType AND IsDeleted<>1

		IF(@MaxPos<>@position) 
	BEGIN 
				UPDATE Metadata_MetadataField 
		SET Position = @position 
		WHERE ForeignId = @foreignId AND ForeignType = @foreignType AND Position=@position + 1 

				UPDATE Metadata_MetadataField 
		SET Position = @position + 1 
		WHERE MetadataId = @metadataId 
	END 

END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_SetTaskStepUpgrade]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_SetTaskStepUpgrade]
	@taskId int,
	@upgradeText nvarchar(max)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE ProcessDefinition_ProjectPlanTask
	SET    StepUpgradeHistory = ISNULL(StepUpgradeHistory,'')+@upgradeText
	WHERE (ProjectPlanTaskId = @taskId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_MoveUpMetadataField]'
GO
CREATE PROCEDURE [dbo].[Metadata_MoveUpMetadataField]
	@metadataId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @foreignId int
	DECLARE @foreignType int 
	DECLARE @position int 
	SELECT @position = Position, @foreignId = ForeignId,  @foreignType = ForeignType
	FROM Metadata_MetadataField 
	WHERE MetadataId=@metadataId 
		IF(@position<>1) 	BEGIN 
				UPDATE Metadata_MetadataField 
		SET Position = @position 
		WHERE ForeignId = @foreignId AND ForeignType = @foreignType AND Position=@position - 1 

				UPDATE Metadata_MetadataField 
		SET Position = @position - 1 
		WHERE MetadataId = @metadataId 
	END 

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_CreateMetadataField]'
GO
CREATE PROCEDURE [dbo].[Metadata_CreateMetadataField]
	@foreignId int, 
	@foreignType int,
	@MetadaType nvarchar(100),
	@IsMandatory bit,
	@ScreenLabel nvarchar(100),
	@DefaultValue nvarchar(100),
	@AllowableValues nvarchar(4000),
	@CssClass nvarchar(50),
	@FormatInfo nvarchar(50),
	@ControlData nvarchar(2000),
	@metadataId int OUTPUT
	
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		DECLARE @position int 
	SET @position = (SELECT MAX(Position) FROM Metadata_MetadataField WHERE ForeignId=@foreignId AND ForeignType=@foreignType AND IsDeleted<>1)+1 
	IF(@position IS NULL) 
	SET @position=1 
	INSERT INTO Metadata_MetadataField
						  (ForeignId, ForeignType, MetadataType, IsMandatory, Position, ScreenLabel, DefaultValue, AllowableValues, CssClass, FormatInfo, ControlData)
	VALUES     (@foreignId,@foreignType,@MetadaType,@IsMandatory,@position,@ScreenLabel,@DefaultValue,@AllowableValues,@CssClass,@FormatInfo,@ControlData)

	SET @metadataId=Scope_Identity()


END




GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_HasMetadataItem]'
GO
CREATE PROCEDURE [dbo].[Metadata_HasMetadataItem] 
	@foreignId int,
	@foreignType int,
	@screenLabel nvarchar(100),
	@metadataId int OUTPUT
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     @metadataId=MetadataId
	FROM         Metadata_MetadataField
	WHERE     (ForeignId = @foreignId) AND (ForeignType = @foreignType) AND (IsDeleted <> 1) AND (ScreenLabel=@screenLabel)

END



GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Metadata_GetBulkMetadataData]'
GO
CREATE PROCEDURE [dbo].[Metadata_GetBulkMetadataData]
	@bulkForeignId int,
	@bulkForeignType int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     Metadata_MetadataField.MetadataId, Metadata_MetadataField.MetadataType, Metadata_MetadataField.IsMandatory, Metadata_MetadataField.Position, 
                      Metadata_MetadataField.ScreenLabel, Metadata_MetadataField.DefaultValue, Metadata_MetadataField.AllowableValues, Metadata_MetadataField.CssClass, 
                      Metadata_MetadataField.FormatInfo, Metadata_MetadataField.ControlData, MetadataData.MetadataDataId, MetadataData.StringValue, MetadataData.IntValue, 
                      MetadataData.BoolValue, MetadataData.DoubleValue,MetadataData.DateValue, MetadataData.DateChanged, MetadataData.ChangedByUserId
FROM         Metadata_MetadataField LEFT OUTER JOIN
                          (SELECT     MetadataDataId, MetadataId, StringValue, IntValue, BoolValue, DoubleValue, DateValue, DateChanged, ChangedByUserId
                            FROM          Metadata_Data
                            WHERE      (ForeignId = @bulkForeignId) AND (ForeignType = @bulkForeignType)) AS MetadataData ON 
                      Metadata_MetadataField.MetadataId = MetadataData.MetadataId
WHERE    (Metadata_MetadataField.IsDeleted <>1)
ORDER BY Metadata_MetadataField.ForeignType DESC,  Metadata_MetadataField.Position

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessHistorySectionMetrics]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessHistorySectionMetrics]
	@userId int,
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


SELECT     ProcessDefinition_ProcessLinkHistory.SectionName, ProcessDefinition_ProcessLinkHistory.LinksToProcessId, ProcessDefinition_ProcessLinkHistory.LinkText, 
                      LinksToProcessHistory.ProcessHistoryId AS LinksToProcessHistoryId
FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
                      ProcessDefinition_ProcessHistory AS LinksToProcessHistory ON 
                      ProcessDefinition_ProcessLinkHistory.LinksToProcessId = LinksToProcessHistory.ProcessId
WHERE     (NOT (ProcessDefinition_ProcessLinkHistory.LinksToProcessId IS NULL)) AND (ProcessDefinition_ProcessLinkHistory.ProcessHistoryId = @processHistoryId) AND 
                      (LinksToProcessHistory.IsFrozenVersion = 1)
AND ( 
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField  WHERE (ForeignType = 16 AND ForeignId=LinksToProcessHistory.ProcessHistoryId))
OR
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField WHERE (ForeignType = 18 AND ForeignId=LinksToProcessHistory.ProcessHistoryId)))


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RemoveUserRoleTaskAssignment]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_RemoveUserRoleTaskAssignment] 	
	@AssignedToId int,
	@RoleId int,
	@TaskId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

		DELETE FROM         ProcessDefinition_ProjectPlanRoleAssignment
	WHERE AssignedToId=@AssignedToId AND RoleProcessId=@RoleId AND  TaskId=@TaskId 

		DECLARE @AssignedManually bit
	SELECT @AssignedManually = AssignedManually
	FROM ProcessDefinition_ProjectPlanTaskAssignment
	WHERE AssignedToId=@AssignedToId AND TaskId=@TaskId

	IF(NOT EXISTS( SELECT RoleAssignmentId FROM ProcessDefinition_ProjectPlanRoleAssignment
					WHERE TaskId=@TaskId AND AssignedToId=@AssignedToId) AND (NOT(@AssignedManually IS NULL) AND @AssignedManually = 0))
	BEGIN
				SELECT 1 AS CanRemoveAssignment
	END
	ELSE
	BEGIN
		SELECT 0 AS CanRemoveAssignment
	END

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessHistoryMetrics]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessHistoryMetrics] 
	@userId int,
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


SELECT     ProcessHistoryId AS LinksToSFid, ProcessHistoryId AS LinksToTFid
FROM         ProcessDefinition_ProcessHistory
WHERE     (ProcessHistoryId = @processHistoryId) AND (
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField  WHERE (ForeignType = 16 AND ForeignId=@processHistoryId))
OR
EXISTS  (SELECT MetadataId FROM Metadata_MetadataField WHERE (ForeignType = 18 AND ForeignId=@processHistoryId)))

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetHistorySteps]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetHistorySteps] 
	@processHistoryId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	
	SELECT	ISNULL(ProcessDefinition_StepHistory.StepName, 
			FreezeCorrectProcesses.ProcessTitle) AS StepName, 
			ProcessDefinition_StepHistory.StepDescription, 
			ProcessDefinition_StepHistory.ChildProcessId, 
			ProcessDefinition_StepHistory.StepType, 
			ProcessDefinition_StepHistory.IterationDescription, 
			ProcessDefinition_StepHistory.OptionalDescription, 
			FreezeCorrectProcesses.PrettyPostTitle, 
			ProcessDefinition_StepHistory.ProcessStepId,
			AltGroup,
			FreezeCorrectProcesses.ProcessTypeId,
			ProcessDefinition_StepHistory.bpmnJson
	FROM ProcessDefinition_StepHistory LEFT OUTER JOIN
		(
SELECT ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProcessHistory.AltGroup, ProcessDefinition_ProcessHistory.ProcessTypeId
FROM  ProcessDefinition_PublishProcess INNER JOIN
         ProcessDefinition_ProcessHistory ON ProcessDefinition_PublishProcess.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
             (SELECT MAX(PublishId) AS LastPublishId
            FROM  ProcessDefinition_PublishProcess AS ProcessDefinition_PublishProcess_1
            WHERE (ProcessHistoryId = @processHistoryId)) AS LastPublish ON ProcessDefinition_PublishProcess.PublishId = LastPublish.LastPublishId

		) AS FreezeCorrectProcesses ON ProcessDefinition_StepHistory.ChildProcessId = FreezeCorrectProcesses.ProcessId 
	WHERE (ProcessDefinition_StepHistory.ProcessHistoryId = @processHistoryId)
	ORDER BY ProcessDefinition_StepHistory.StepPosition


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUserRoleAssignments]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetUserRoleAssignments] 
	@userId int,
	@taskId int 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.ProjectPlanId, ProcessDefinition_ProcessHistory.ProcessHistoryId, 
                      ProcessDefinition_ProcessHistory.ProcessTitle
FROM         ProcessDefinition_ProjectPlanRoleAssignment INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanRoleAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProjectProcessVersion ON ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId AND
                       ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectProcessVersion.ProjectPlanId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (@taskId IS NULL) AND (ProcessDefinition_ProjectPlanRoleAssignment.AssignedToId = @userId) OR
                      (ProcessDefinition_ProjectPlanRoleAssignment.AssignedToId = @userId) AND (ProcessDefinition_ProjectPlanRoleAssignment.TaskId = @taskId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_AssignTask]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_AssignTask] 
	@AssignedById int,
	@AssignedToId int,
	@projectId int,
	@TaskId int,
	@AssignmentNote nvarchar(max),
	@GroupingGuid uniqueidentifier,
	@RoleProcessId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @AssignmentMade bit
	SET @AssignmentMade = 0

	IF(NOT EXISTS(SELECT AssignedTaskId FROM ProcessDefinition_ProjectPlanTaskAssignment 
					WHERE TaskId=@TaskId AND AssignedToId=@AssignedToId))
	BEGIN
		INSERT INTO ProcessDefinition_ProjectPlanTaskAssignment(AssignedById, AssignedToId, ProjectId,TaskId, 
			AssignmentNote, GroupingGuid, AssignedManually)
		VALUES     (@AssignedById,@AssignedToId,@projectId,@TaskId,@AssignmentNote, @GroupingGuid,
			CASE WHEN @RoleProcessId IS NULL THEN 1 ELSE 0 END)

		SET @AssignmentMade = 1
	END

	IF(NOT(@RoleProcessId IS NULL) AND NOT EXISTS( SELECT RoleAssignmentId FROM ProcessDefinition_ProjectPlanRoleAssignment
					WHERE TaskId=@TaskId AND AssignedToId=@AssignedToId AND RoleProcessId=@RoleProcessId))
	BEGIN
		INSERT INTO ProcessDefinition_ProjectPlanRoleAssignment(TaskId, RoleProcessId, AssignedToId, AssignedById,
			AssignmentNote, GroupingGuid)
		VALUES (@TaskId, @RoleProcessId, @AssignedToId, @AssignedById, @AssignmentNote, @GroupingGuid)

		SET @AssignmentMade = 1
	END

	IF(@AssignmentMade = 1)
	BEGIN
		SELECT     Account_User.DisplayName, Account_User.MemberEmailAddress, ProcessDefinition_ProjectPlanTaskAssignment.AssignmentNote, 
                      ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlan.ProjectPlanId AS ProjectId, ProcessDefinition_ProjectPlan.ProjectPlanName
		FROM         Account_User INNER JOIN
                      ProcessDefinition_ProjectPlanTaskAssignment ON Account_User.UserId = ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanTaskAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
		WHERE TaskId=@TaskId AND Account_User.UserId=@AssignedToId
	END
END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetLinkedHistoryProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetLinkedHistoryProcesses] 
	@processId int,
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	
SELECT     ProcessDefinition_ProcessLinkHistory.ProcessLinkHistoryId, ProcessDefinition_ProcessLinkHistory.ProcessId, ProcessDefinition_ProcessLinkHistory.SectionName, 
                      ProcessDefinition_ProcessLinkHistory.LinkUri, ProcessDefinition_ProcessLinkHistory.FullLinkUri, ProcessDefinition_ProcessLinkHistory.LinkText, 
                      ProcessDefinition_ProcessHistory.PrettyPostTitle, 
		ProcessDefinition_ProcessHistory.ProcessTitle, ProcessTypeId, LinksToProcessId, LinkType, SectionDirection
FROM         ProcessDefinition_ProcessLinkHistory LEFT OUTER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProcessLinkHistory.LinksToProcessId = ProcessDefinition_ProcessHistory.ProcessId
WHERE     (ProcessDefinition_ProcessLinkHistory.ProcessId = @processId) 
			AND ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))
			
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetTaskAssignments]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetTaskAssignments] 
	@taskId int 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

SELECT     ProcessDefinition_ProjectPlanTaskAssignment.AssignedTaskId, ProcessDefinition_ProjectPlanTaskAssignment.AssignmentNote, 
                      ProcessDefinition_ProjectPlanTaskAssignment.TaskId, ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId, 
                      ProcessDefinition_ProjectPlanTaskAssignment.AssignedDate, Account_User.DisplayName, Account_User.MemberEmailAddress
FROM         ProcessDefinition_ProjectPlanTaskAssignment INNER JOIN
                      Account_User ON ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = Account_User.UserId
WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.TaskId = @taskId)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMyAssignedRoles]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMyAssignedRoles] 
	@projectPlanId int,
	@userId int

WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
SELECT     ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
                      ProcessDefinition_ProjectPlanRoleAssignment.TaskId, ProcessDefinition_ProjectPlanTask.TaskName
FROM         ProcessDefinition_ProjectPlanRoleAssignment INNER JOIN
                      ProcessDefinition_ProjectProcessVersion ON 
                      ProcessDefinition_ProjectPlanRoleAssignment.RoleProcessId = ProcessDefinition_ProjectProcessVersion.ProcessId INNER JOIN
                      ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanRoleAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectProcessVersion.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
                      ProcessDefinition_ProjectPlanRoleAssignment.TaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId
WHERE     (ProcessDefinition_ProjectPlanRoleAssignment.AssignedToId = @userId) AND (ProcessDefinition_ProjectProcessVersion.ProjectPlanId = @projectPlanId) AND 
                      (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId)
ORDER BY ProcessDefinition_ProcessHistory.ProcessTitle, TaskName

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RemoveTaskAssignments]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_RemoveTaskAssignments] 	
	@AssignedToId int,
	@TaskId int 
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     Account_User.DisplayName, Account_User.MemberEmailAddress, ProcessDefinition_ProjectPlanTaskAssignment.AssignmentNote, 
                  ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlan.ProjectPlanId AS ProjectId, ProcessDefinition_ProjectPlan.ProjectPlanName
	FROM         Account_User INNER JOIN
                  ProcessDefinition_ProjectPlanTaskAssignment ON Account_User.UserId = ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId INNER JOIN
                  ProcessDefinition_ProjectPlanTask ON ProcessDefinition_ProjectPlanTaskAssignment.TaskId = ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId INNER JOIN
                  ProcessDefinition_ProjectPlan ON ProcessDefinition_ProjectPlanTask.ProjectPlanId = ProcessDefinition_ProjectPlan.ProjectPlanId
	WHERE TaskId=@TaskId AND Account_User.UserId=@AssignedToId

		DELETE FROM         ProcessDefinition_ProjectPlanTaskAssignment
	WHERE TaskId=@TaskId AND AssignedToId=@AssignedToId

		DELETE FROM         ProcessDefinition_ProjectPlanRoleAssignment
	WHERE TaskId=@TaskId AND AssignedToId=@AssignedToId

END
GO

IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetProcessPrettyTitles]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetProcessPrettyTitles]
(
      @repositoryName nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     PrettyPostTitle, ProcessId
	FROM         ProcessDefinition_Process
	WHERE     (ForeignId = @RepositoryId)
	ORDER BY PrettyPostTitle
 
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_ClearSteps]'
GO

CREATE PROCEDURE [dbo].[ProcessDefinition_ClearSteps] 
	@ParentProcessId int,
	@stepDefinitionVersion int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;


	DELETE FROM ProcessDefinition_Step
	WHERE     (ParentProcessId = @ParentProcessId)

	DELETE FROM ProcessDefinition_StepPredecessor
	WHERE     (ParentProcessId = @ParentProcessId)

		UPDATE ProcessDefinition_Process
	SET StepDefinitionVersion = @stepDefinitionVersion
	WHERE ProcessId = @ParentProcessId

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateProcessPrettyTitle]'
GO

 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateProcessPrettyTitle]
(
     @processId int,
      @PrettyPostTitle nvarchar(256)
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	UPDATE    ProcessDefinition_ProcessHistory
	SET             PrettyPostTitle=@PrettyPostTitle
	WHERE     (ProcessId = @processId)

	UPDATE    ProcessDefinition_Process
	SET             PrettyPostTitle=@PrettyPostTitle
	WHERE     (ProcessId = @processId)


END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetSteps]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetSteps] 
	@ParentProcessId int,
	@useFrozen bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	

	DECLARE @CorrectProcessHistoryId int
	SELECT @CorrectProcessHistoryId =  ProcessHistoryId
	FROM ProcessDefinition_ProcessHistory
	WHERE   (ProcessDefinition_ProcessHistory.ProcessId = @ParentProcessId) AND
		 ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))

	SELECT     ISNULL(ProcessDefinition_StepHistory.StepName, FreezeCorrectProcesses.ProcessTitle) AS StepName, 
				ProcessDefinition_StepHistory.StepDescription, 
				ProcessDefinition_StepHistory.ChildProcessId, 
				ProcessDefinition_StepHistory.StepType, 
				ProcessDefinition_StepHistory.IterationDescription, 
				ProcessDefinition_StepHistory.OptionalDescription, 
				FreezeCorrectProcesses.PrettyPostTitle, 
				ProcessDefinition_StepHistory.ProcessStepId,
				AltGroup,
				FreezeCorrectProcesses.ProcessTypeId,
				ProcessDefinition_StepHistory.bpmnJson
	FROM ProcessDefinition_StepHistory LEFT OUTER JOIN
		(
			SELECT ProcessId, ProcessTitle, PrettyPostTitle, AltGroup, ProcessTypeId
			FROM ProcessDefinition_ProcessHistory
			WHERE   ((@useFrozen = 1 AND IsFrozenVersion = 1) OR (@useFrozen = 0 AND IsLatestVersion = 1))
		) AS FreezeCorrectProcesses ON ProcessDefinition_StepHistory.ChildProcessId = FreezeCorrectProcesses.ProcessId 
	WHERE (ProcessDefinition_StepHistory.ProcessHistoryId = @CorrectProcessHistoryId)
	ORDER BY ProcessDefinition_StepHistory.StepPosition

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_StepsWithoutTailoring]'
GO
CREATE PROCEDURE [dbo].[Review_StepsWithoutTailoring]
		@repositoryName varchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

    	SELECT     ProcessDefinition_Process.ProcessTitle AS tf_Process, 
				ProcessDefinition_Step.StepName as tf_Step,
				CASE WHEN ((ProcessDefinition_Step.StepType & 4) > 0) THEN 'Optional' ELSE '' END AS dd_Optional,
				CASE WHEN ((ProcessDefinition_Step.StepType & 8) > 0) THEN 'Iterative' ELSE '' END AS dd_Iterative,
				'~/' + ProcessDefinition_Process.PrettyPostTitle AS link_Process
	FROM         ProcessDefinition_Process INNER JOIN
						  ProcessDefinition_Step ON ProcessDefinition_Process.ProcessId = ProcessDefinition_Step.ParentProcessId
	WHERE     (ProcessDefinition_Process.ForeignId = @RepositoryId) AND
		((ProcessDefinition_Step.StepType & 12) > 0) AND
		((ProcessDefinition_Step.StepDescription IS NULL) OR LEN(ProcessDefinition_Step.StepDescription) = 0 )


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_HasTaskAccess]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_HasTaskAccess] 
(
	@TaskId int,
	@userId int
)
WITH ENCRYPTION AS
BEGIN
		DECLARE @projectPlanId int

		SELECT   @projectPlanId=  ProjectPlanId
	FROM         ProcessDefinition_ProjectPlanTask
	WHERE     (ProjectPlanTaskId = @TaskId)

	DECLARE @HasProjectAccess bit
	SET @HasProjectAccess = dbo.ProcessDefinition_HasProjectPlanAccess(@projectPlanId, @userId)

	DECLARE @HasTaskAccess bit
		DECLARE @AssignedToId int
	SELECT  TOP 1 @AssignedToId=  ProcessDefinition_ProjectPlanTaskAssignment.AssignedTaskId
FROM         ProcessDefinition_ProjectPlanTask RIGHT OUTER JOIN
                      ProcessDefinition_ProjectPlanTaskAssignment ON ProcessDefinition_ProjectPlanTask.ParentTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId)
			AND (ProcessDefinition_ProjectPlanTaskAssignment.TaskId=@TaskId OR
	(
(ProcessDefinition_ProjectPlanTask.TaskProcessId IS NULL) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = @TaskId)))

	IF(@AssignedToId IS NOT NULL)
	BEGIN
				SET @HasTaskAccess=1
	END
	ELSE
	BEGIN
		DECLARE @MemberRole int
		SELECT     @MemberRole=ProcessDefinition_Member.MemberRole
		FROM         ProcessDefinition_Member INNER JOIN
							  ProcessDefinition_Project ON ProcessDefinition_Member.RepositoryId = ProcessDefinition_Project.RepositoryId INNER JOIN
							  ProcessDefinition_ProjectPlan ON ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectPlan.ProjectId
		WHERE     (ProcessDefinition_Member.UserId = @userId) AND (ProcessDefinition_ProjectPlan.ProjectPlanId = @projectPlanId)

		IF(@MemberRole>=3)
		BEGIN
						SET @HasTaskAccess=1
		END

	END

	SELECT @HasTaskAccess AS HasTaskAccess, @HasProjectAccess AS HasProjectAccess
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_CreateMember]'
GO
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_CreateMember]
(
     @repositoryName nvarchar(256),
      @userId int,
      @MemberRole int,
	@UserAssigned bit
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @MemberId int

	SELECT     @MemberId=MemberId
	FROM         ProcessDefinition_Member
	WHERE     (RepositoryId = @RepositoryId) AND (UserId = @userId)
 
	DECLARE @newId int
	SET @newId=@MemberId 
	IF(@MemberId IS NULL)
	BEGIN
		INSERT INTO ProcessDefinition_Member
		(
			RepositoryId, 
			UserId, 
			MemberRole,
			UserAssigned
		) VALUES (
			@RepositoryId, 
			@userId, 
			@MemberRole,
			@UserAssigned
		)
		SET @newId = Scope_Identity()

	END
	ELSE
	BEGIN
		UPDATE ProcessDefinition_Member 
		SET MemberRole=@MemberRole, UserAssigned=@UserAssigned
		WHERE MemberId=@MemberId
	END

	RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_TaskCanStart]'
GO


CREATE PROCEDURE [dbo].[Review_TaskCanStart] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL



SELECT     PP.ProjectPlanName AS dd_ProjectName, 
			PPT.EstimatedStartDate AS dtl_EstimatedStartDate, 
			PPT.TaskName AS tf_Task, 
			'~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(PPT.ProjectPlanId AS nvarchar(12)) + '|' + CAST(PPT.ParentTaskId AS nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
                      ProcessDefinition_ProjectPlan AS PP ON PP.ProjectPlanId = PPT.ProjectPlanId INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS UnRemoved ON PPT.ProjectPlanTaskId = UnRemoved.ProjectPlanTaskId LEFT OUTER JOIN
                      ProcessDefinition_ProcessHistory ON PPT.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (PP.ProjectId = @projectId) AND 
(PPT.CurrentStatus = 1) AND
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId)) AND
(dbo.ProcessDefinition_CanTaskStart(PPT.ProjectPlanTaskId) = 1) AND
PPT.ProjectPlanTaskId IN (SELECT ProjectPlanTaskId FROM dbo.ProcessDefinition_GetUnremovedTasks(PP.ProjectPlanId))

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMyAssignedTasks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMyAssignedTasks] 

	@projectPlanId int,
	@userId int

WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
SELECT     ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, 
                      ProcessDefinition_ProjectPlanTask.ActualStartDate, ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, 
                      ProcessDefinition_ProjectPlanTask.StatusNotes, ProcessDefinition_ProjectPlanTask.TaskProgressPc, ProcessDefinition_ProcessHistory.ProcessTitle, 
                      ProcessDefinition_ProcessHistory.DescriptionSnippet, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId,
	CASE WHEN CurrentStatus = 1 AND NOT(ProcessDefinition_ProjectPlanTask.EstimatedStartDate IS NULL) AND ProcessDefinition_ProjectPlanTask.EstimatedStartDate <= GetUtcDate() THEN 1  		WHEN CurrentStatus = 2 AND NOT(ProcessDefinition_ProjectPlanTask.EstimatedEndDate IS NULL) AND ProcessDefinition_ProjectPlanTask.EstimatedEndDate <= GetUtcDate() THEN 2 		WHEN CurrentStatus = 2 THEN 3  		WHEN CurrentStatus = 1 THEN 4  		WHEN CurrentStatus >= 3 THEN 5 END 	 AS TaskGroup,
	CASE WHEN CurrentStatus = 1 AND NOT(ProcessDefinition_ProjectPlanTask.EstimatedStartDate IS NULL) AND ProcessDefinition_ProjectPlanTask.EstimatedStartDate <= GetUtcDate() THEN ProcessDefinition_ProjectPlanTask.EstimatedStartDate  		WHEN CurrentStatus = 2 AND NOT(ProcessDefinition_ProjectPlanTask.EstimatedEndDate IS NULL) AND ProcessDefinition_ProjectPlanTask.EstimatedEndDate <= GetUtcDate() THEN ProcessDefinition_ProjectPlanTask.EstimatedEndDate 		WHEN CurrentStatus = 2 THEN COALESCE (ProcessDefinition_ProjectPlanTask.EstimatedEndDate, DATEADD(y, 20, GETUTCDATE()))  		WHEN CurrentStatus = 1 THEN COALESCE (ProcessDefinition_ProjectPlanTask.EstimatedStartDate, DATEADD(y, 20, GETUTCDATE()))  		WHEN CurrentStatus >= 3 THEN ProcessDefinition_ProjectPlanTask.ActualEndDate END 	 AS TaskDate,
	dbo.ProcessDefinition_CanTaskStart(ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId) as CanStart
FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
                      ProcessDefinition_ProjectPlanTaskAssignment ON 
                      ((ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId)
							OR (ProcessDefinition_ProjectPlanTask.ParentTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId AND ProcessDefinition_ProjectPlanTask.TaskProcessId IS NULL))
					INNER JOIN
                      dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
                      ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId LEFT OUTER JOIN
                      ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (ProcessDefinition_ProjectPlanTaskAssignment.AssignedToId = @userId) AND (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId) AND 
                   (   (ProcessDefinition_ProjectPlanTask.CurrentStatus <= 2) OR (ActualEndDate < DateAdd(w, 2, GetUtcDate()) ) )
ORDER BY TaskGroup, TaskDate, TaskName
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_RemoveMember]'
GO
 
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_RemoveMember]
(
     @repositoryName nvarchar(256),
      @userId int
)
WITH ENCRYPTION AS
BEGIN
 
	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

               SET NOCOUNT ON;
 
     DELETE FROM ProcessDefinition_Member WHERE 
     RepositoryId=@RepositoryId AND
     UserId= @userId
	
	DELETE FROM ProcessDefinition_ProjectMember WHERE ProjectMemberId IN
	(
	SELECT     ProcessDefinition_ProjectMember.ProjectMemberId
	FROM         ProcessDefinition_Project INNER JOIN
						  ProcessDefinition_ProjectMember ON ProcessDefinition_Project.ProjectId = ProcessDefinition_ProjectMember.ProjectId
	WHERE     (ProcessDefinition_Project.RepositoryId = @RepositoryId) AND (ProcessDefinition_ProjectMember.UserId = @userId)
	)

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Account_DeleteUser]'
GO
CREATE PROCEDURE [dbo].[Account_DeleteUser] 
	@userId int
 WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	UPDATE Account_User SET IsDeleted=1 WHERE UserId=@userId


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[MetaWeblog_MediaObject]'
GO
CREATE TABLE [dbo].[MetaWeblog_MediaObject]
(
[MetaWeblogMediaObjectId] [int] NOT NULL IDENTITY(1, 1),
[MediaObjectName] [nvarchar] (max) NOT NULL,
[MediaObjectType] [nvarchar] (max) NOT NULL,
[ForeignId] [int] NOT NULL,
[ForeignType] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_MetaWeblog_MediaObject] on [dbo].[MetaWeblog_MediaObject]'
GO
ALTER TABLE [dbo].[MetaWeblog_MediaObject] ADD CONSTRAINT [PK_MetaWeblog_MediaObject] PRIMARY KEY CLUSTERED  ([MetaWeblogMediaObjectId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[MetaWeblog_CreateMediaObject]'
GO
 
 
CREATE PROCEDURE [dbo].[MetaWeblog_CreateMediaObject]
(
     @MediaObjectName nvarchar(max),
      @MediaObjectType nvarchar(max),
      @foreignId int,
      @foreignType int
)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;
 
     INSERT INTO MetaWeblog_MediaObject
      (
            MediaObjectName, 
            MediaObjectType, 
            ForeignId, 
            ForeignType
      ) VALUES (
            @MediaObjectName, 
            @MediaObjectType, 
            @foreignId, 
            @foreignType
      )
 
     DECLARE @newId int
     SET @newId = Scope_Identity()
     RETURN @newId
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetUnassignedTasks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetUnassignedTasks] 

	@projectPlanId int

WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	SELECT     ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, 
						  ProcessDefinition_ProjectPlanTask.ActualStartDate, ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, 
						  ProcessDefinition_ProjectPlanTask.StatusNotes, ProcessDefinition_ProjectPlanTask.TaskProgressPc, ProcessDefinition_ProcessHistory.ProcessTitle, 
						  ProcessDefinition_ProcessHistory.DescriptionSnippet, ProcessDefinition_ProcessHistory.PrettyPostTitle, ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
	FROM         ProcessDefinition_ProjectPlanTask INNER JOIN
						  ProcessDefinition_ProcessHistory ON ProcessDefinition_ProjectPlanTask.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId INNER JOIN
						  dbo.ProcessDefinition_GetUnremovedTasks(@projectPlanId) AS ProcessDefinition_GetUnremovedTasks_1 ON 
						  ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_GetUnremovedTasks_1.ProjectPlanTaskId LEFT OUTER JOIN
						  ProcessDefinition_ProjectPlanTaskAssignment ON 
						  ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId = ProcessDefinition_ProjectPlanTaskAssignment.TaskId
	WHERE     (ProcessDefinition_ProjectPlanTask.ProjectPlanId = @projectPlanId)
	GROUP BY ProcessDefinition_ProjectPlanTask.TaskName, ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.EstimatedEndDate, 
						  ProcessDefinition_ProjectPlanTask.ActualStartDate, ProcessDefinition_ProjectPlanTask.ActualEndDate, ProcessDefinition_ProjectPlanTask.CurrentStatus, 
						  ProcessDefinition_ProjectPlanTask.StatusNotes, ProcessDefinition_ProjectPlanTask.TaskProgressPc, ProcessDefinition_ProcessHistory.ProcessTitle, 
						  ProcessDefinition_ProcessHistory.DescriptionSnippet, ProcessDefinition_ProcessHistory.PrettyPostTitle, 
						  ProcessDefinition_ProjectPlanTask.ProjectPlanTaskId
	HAVING      (ProcessDefinition_ProjectPlanTask.CurrentStatus <= 2) AND (COUNT(ProcessDefinition_ProjectPlanTaskAssignment.AssignedTaskId) = 0)
	ORDER BY ProcessDefinition_ProjectPlanTask.EstimatedStartDate, ProcessDefinition_ProjectPlanTask.ActualStartDate

END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_GetMembers]'
GO

 
 
 
CREATE PROCEDURE [dbo].[ProcessDefinition_GetMembers]
     @repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
 
               SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
 

	SELECT     ProcessDefinition_Member.MemberId, ProcessDefinition_Member.UserId, ProcessDefinition_Member.MemberRole, Account_User.DisplayName,
						  Account_User.MemberEmailAddress, CAST('' AS varchar(256)) AS GravatarUrl
	FROM         ProcessDefinition_Member INNER JOIN
						  Account_User ON ProcessDefinition_Member.UserId = Account_User.UserId
	WHERE     (ProcessDefinition_Member.RepositoryId = @RepositoryId) AND (Account_User.IsDeleted=0)
	ORDER BY Account_User.MemberEmailAddress 

END

GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[Review_TaskShouldNotStarted]'
GO


CREATE PROCEDURE [dbo].[Review_TaskShouldNotStarted] 
		@projectId int,
	@projectPlanId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

IF(@projectPlanId = 0)
	SET @projectPlanId = NULL

SELECT     PP.ProjectPlanName AS dd_ProjectName, 
			PPT.TaskName AS tf_Task, 
			PPT.EstimatedStartDate AS dtl_EstimatedStartDate, 
			PPT.ActualStartDate AS dtl_ActualStartDate, 
                      '~/Project/{0:scramble,pPl}/Framed/{1}|' + CAST(PPT.ProjectPlanId AS nvarchar(12)) + '|' + CAST(PPT.ParentTaskId AS nvarchar(12)) AS flink_Link
FROM         ProcessDefinition_ProjectPlanTask AS PPT INNER JOIN
                      ProcessDefinition_ProjectPlan AS PP ON PP.ProjectPlanId = PPT.ProjectPlanId LEFT OUTER JOIN
                      ProcessDefinition_ProcessHistory ON PPT.ProcessHistoryId = ProcessDefinition_ProcessHistory.ProcessHistoryId
WHERE     (PP.ProjectId = @projectId) AND 
(PPT.CurrentStatus > 1) AND 
( (@projectPlanId IS NULL) OR (PPT.ProjectPlanId = @projectPlanId)) AND
(dbo.ProcessDefinition_CanTaskStart(PPT.ProjectPlanTaskId) = 0) AND
PPT.ProjectPlanTaskId IN (SELECT ProjectPlanTaskId FROM dbo.ProcessDefinition_GetUnremovedTasks(PP.ProjectPlanId))

END


GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_UpdateMissingLinks]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_UpdateMissingLinks] 
	@linkUri nvarchar(1024), 
	@processId int,
	@repositoryName nvarchar(256)
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)
	IF(@RepositoryId IS NOT NULL)
	BEGIN

						UPDATE ProcessDefinition_ProcessLinkHistory
			SET LinksToProcessId=@processId
			FROM         ProcessDefinition_ProcessLinkHistory INNER JOIN
                          (SELECT     ProcessDefinition_ProcessLink.ProcessId, ProcessDefinition_Process.MinorVersion
                            FROM          ProcessDefinition_ProcessLink INNER JOIN
                                                   ProcessDefinition_Process ON ProcessDefinition_ProcessLink.ProcessId = ProcessDefinition_Process.ProcessId
                            WHERE      (ProcessDefinition_Process.ForeignId = @RepositoryId) AND (ProcessDefinition_Process.ForeignType = 7) AND 
                                                   (ProcessDefinition_ProcessLink.LinkUri = @linkUri) AND ((ProcessDefinition_ProcessLink.LinkType & 1) = 0)) AS UpdateLinks ON ProcessDefinition_ProcessLinkHistory.ProcessId = UpdateLinks.ProcessId AND 
                      ProcessDefinition_ProcessLinkHistory.MinorVersion = UpdateLinks.MinorVersion
			WHERE ProcessDefinition_ProcessLinkHistory.LinkUri = @linkUri


						UPDATE ProcessDefinition_ProcessLink
			SET LinksToProcessId=@processId
            FROM          ProcessDefinition_ProcessLink INNER JOIN
                                   ProcessDefinition_Process ON ProcessDefinition_ProcessLink.ProcessId = ProcessDefinition_Process.ProcessId
            WHERE      (ProcessDefinition_Process.ForeignId = @RepositoryId) AND (ProcessDefinition_Process.ForeignType = 7) AND 
                                   ProcessDefinition_ProcessLink.LinkUri = @linkUri AND ((ProcessDefinition_ProcessLink.LinkType & 1) = 0)

	END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[ProcessDefinition_Announcement]'
GO
CREATE TABLE [dbo].[ProcessDefinition_Announcement]
(
[AnnouncementId] [int] NOT NULL IDENTITY(1, 1),
[AnnouncementTitle] [nvarchar] (256) NOT NULL,
[AnnouncementText] [nvarchar] (max) NOT NULL,
[AnnouncementIcon] [nvarchar] (256) NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_ProcessDefinition_Announcement] on [dbo].[ProcessDefinition_Announcement]'
GO
ALTER TABLE [dbo].[ProcessDefinition_Announcement] ADD CONSTRAINT [PK_ProcessDefinition_Announcement] PRIMARY KEY CLUSTERED  ([AnnouncementId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding foreign keys to [dbo].[Metadata_DataHistory]'
GO
ALTER TABLE [dbo].[Metadata_DataHistory] ADD CONSTRAINT [FK_Metadata_DataHistory_Metadata_DataHistoryChangeset] FOREIGN KEY ([MetadataDataHistoryChangesetId]) REFERENCES [dbo].[Metadata_DataHistoryChangeset] ([MetadataDataHistoryChangesetId])
ALTER TABLE [dbo].[Metadata_DataHistory] ADD CONSTRAINT [FK_Metadata_DataHistory_Metadata_Data] FOREIGN KEY ([MetadataDataId]) REFERENCES [dbo].[Metadata_Data] ([MetadataDataId])
ALTER TABLE [dbo].[Metadata_DataHistory] ADD CONSTRAINT [FK_Metadata_DataHistory_Metadata_MetadataField] FOREIGN KEY ([MetadataId]) REFERENCES [dbo].[Metadata_MetadataField] ([MetadataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding foreign keys to [dbo].[Metadata_Data]'
GO
ALTER TABLE [dbo].[Metadata_Data] ADD CONSTRAINT [FK_Metadata_Data_Metadata_MetadataField] FOREIGN KEY ([MetadataId]) REFERENCES [dbo].[Metadata_MetadataField] ([MetadataId])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating extended properties'
GO
EXEC sp_addextendedproperty N'TableDescription', N'A wrapper around the dot net account management', 'SCHEMA', N'dbo', 'TABLE', N'Account_User', NULL, NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
EXEC sp_addextendedproperty N'MS_Description', N'1 = excluded, 2 = Hide Properties, 4 = Optional', 'SCHEMA', N'dbo', 'TABLE', N'ProcessDefinition_ProcessLink', 'COLUMN', N'LinkType'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
COMMIT TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding full text indexing to tables'
GO
CREATE FULLTEXT INDEX ON [dbo].[ProcessDefinition_ProcessHistory] KEY INDEX [PK_ProcessDefintion_ProcessHistory] ON [ProcessDefinitionFtIndex]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
CREATE FULLTEXT INDEX ON [dbo].[ProcessDefinition_Process] KEY INDEX [PK_ProcessDefintion_Process] ON [ProcessDefinitionFtIndex]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
CREATE FULLTEXT INDEX ON [dbo].[ProcessDefinition_StepHistory] KEY INDEX [PK_ProcessDefinition_StepHistory] ON [ProcessDefinitionFtIndex]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
CREATE FULLTEXT INDEX ON [dbo].[ProcessDefinition_Step] KEY INDEX [PK_ProcessDefinition_Step] ON [ProcessDefinitionFtIndex]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
CREATE FULLTEXT INDEX ON [dbo].[ProcessDefinition_UploadedFile] KEY INDEX [PK_ProcessDefinition_UploadedFile] ON [ProcessDefinitionFtIndex]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Adding full text indexing to columns'
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_ProcessHistory] ADD ([ProcessDescription] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_ProcessHistory] ADD ([ProcessTitle] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Process] ADD ([ProcessDescription] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Process] ADD ([ProcessTitle] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_StepHistory] ADD ([StepName] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_StepHistory] ADD ([StepDescription] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Step] ADD ([StepName] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Step] ADD ([StepDescription] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_UploadedFile] ADD ([FileContent] LANGUAGE 1033)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_ProcessHistory] ENABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Process] ENABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_StepHistory] ENABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_Step] ENABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
ALTER FULLTEXT INDEX ON [dbo].[ProcessDefinition_UploadedFile] ENABLE
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
DECLARE @Success AS BIT
SET @Success = 1
SET NOEXEC OFF
IF (@Success = 1) PRINT 'The database update succeeded'
ELSE BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
	PRINT 'The database update failed'
END
GO

PRINT N'Creating [dbo].[Search_ProjectSearch]'
GO
CREATE PROCEDURE [dbo].[Search_ProjectSearch] 
	@searchFor nvarchar(500),
	@repositoryName nvarchar(256),
	@projectPlanId int,
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;



		SELECT	ProcessDefinition_ProcessHistory_1.ProcessId,
				ProcessDefinition_ProcessHistory_1.PrettyPostTitle, 
				ProcessDefinition_ProcessHistory_1.MinorVersion, 
				ProcessDefinition_ProcessHistory_1.IsLatestVersion, 
				ProcessDefinition_ProcessHistory_1.ProcessTitle, 
				ProcessDefinition_ProcessHistory_1.DescriptionSnippet,
				dbo.ProcessDefinition_HasPostAccess(PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess
	FROM         (SELECT     ProcessHistoryId
						   FROM          ProcessDefinition_ProjectProcessVersion
						   WHERE      (ProjectPlanId = @projectPlanId) AND (ProcessHistoryId IS NOT NULL)
						   UNION
						   SELECT     ProcessHistoryId
						   FROM         ProcessDefinition_ProjectPlanTask
						   WHERE     (ProjectPlanId = @projectPlanId) AND (ProcessHistoryId IS NOT NULL)) AS ProjProcesses INNER JOIN
							  (SELECT     TOP (100) PERCENT ProcessDefinition_ProcessHistory.ProcessId, MAX(ProcessDefinition_ProcessHistory.MinorVersion) AS LatestMinorVersion
								FROM          ProcessDefinition_ProcessHistory INNER JOIN
													   ProcessDefinition_Repository ON ProcessDefinition_ProcessHistory.ForeignId = ProcessDefinition_Repository.RepositoryId
								WHERE      (ProcessDefinition_Repository.RepositoryName = @repositoryName)
								AND CONTAINS(ProcessDefinition_ProcessHistory.*, @searchFor)
								GROUP BY ProcessDefinition_ProcessHistory.ProcessId) AS LatestFoundProcesses INNER JOIN
						  ProcessDefinition_ProcessHistory AS ProcessDefinition_ProcessHistory_1 ON 
						  LatestFoundProcesses.LatestMinorVersion = ProcessDefinition_ProcessHistory_1.MinorVersion AND 
						  LatestFoundProcesses.ProcessId = ProcessDefinition_ProcessHistory_1.ProcessId ON 
						  ProjProcesses.ProcessHistoryId = ProcessDefinition_ProcessHistory_1.ProcessHistoryId
	ORDER BY ProcessDefinition_ProcessHistory_1.ProcessTitle





END


GO
IF @@ERROR <> 0 SET NOEXEC ON
PRINT N'Creating [dbo].[Search_RepositorySearch]'
GO
CREATE PROCEDURE [dbo].[Search_RepositorySearch] 
	@searchFor nvarchar(500),
	@repositoryName nvarchar(256),
	@userId int,
	@usePublished bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;
	DECLARE @StrippedTitle nvarchar(500)
	SET @StrippedTitle=REPLACE(@searchFor,'"','')

	IF(@usePublished=0)
	BEGIN
	    SELECT			ProcessDefinition_ProcessHistory_1.ProcessId,
					    ProcessDefinition_ProcessHistory_1.PrettyPostTitle,
					    ProcessDefinition_ProcessHistory_1.MinorVersion, 
					    ProcessDefinition_ProcessHistory_1.IsLatestVersion,
					    ProcessDefinition_ProcessHistory_1.ProcessTitle,
					    ProcessDefinition_ProcessHistory_1.DescriptionSnippet,
					    1 AS HasPostAccess
	    FROM         (
		    SELECT     TOP (100) PERCENT ProcessDefinition_ProcessHistory.ProcessId, MAX(ProcessDefinition_ProcessHistory.MinorVersion) AS LatestMinorVersion
			    FROM          ProcessDefinition_ProcessHistory INNER JOIN
				    ProcessDefinition_Repository ON ProcessDefinition_ProcessHistory.ForeignId = ProcessDefinition_Repository.RepositoryId
			    WHERE     (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND
						    CONTAINS(ProcessDefinition_ProcessHistory.*, @searchFor)
							  GROUP BY ProcessDefinition_ProcessHistory.ProcessId
							  ) AS LatestFoundProcesses INNER JOIN
				    ProcessDefinition_ProcessHistory AS ProcessDefinition_ProcessHistory_1 ON 
							 LatestFoundProcesses.LatestMinorVersion = ProcessDefinition_ProcessHistory_1.MinorVersion AND 
							 LatestFoundProcesses.ProcessId = ProcessDefinition_ProcessHistory_1.ProcessId INNER JOIN
				    ProcessDefinition_Process ON LatestFoundProcesses.ProcessId = ProcessDefinition_Process.ProcessId
	    WHERE ProcessDefinition_Process.IsDeleted=0
	    ORDER BY CASE WHEN ProcessDefinition_ProcessHistory_1.ProcessTitle=@StrippedTitle THEN 1 ELSE 2 END,ProcessDefinition_ProcessHistory_1.ProcessTitle
    END
    ELSE
    BEGIN

    
	   DECLARE @repositoryId int
	   SET @repositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	   DECLARE @lastPublishedId int

	   SELECT @lastPublishedId=MAX(PublishId)
	   FROM  ProcessDefinition_Publish
	   WHERE (RepositoryId = @repositoryId)

			 SELECT ProcessDefinition_ProcessHistory_1.ProcessId, ProcessDefinition_ProcessHistory_1.PrettyPostTitle, ProcessDefinition_ProcessHistory_1.MinorVersion, ProcessDefinition_ProcessHistory_1.IsLatestVersion, ProcessDefinition_ProcessHistory_1.ProcessTitle, ProcessDefinition_ProcessHistory_1.DescriptionSnippet, 1 AS HasPostAccess
	   FROM  (SELECT TOP (100) PERCENT ProcessDefinition_ProcessHistory.ProcessId, MAX(ProcessDefinition_ProcessHistory.MinorVersion) AS LatestMinorVersion
			  FROM  ProcessDefinition_ProcessHistory INNER JOIN
					 ProcessDefinition_Repository ON ProcessDefinition_ProcessHistory.ForeignId = ProcessDefinition_Repository.RepositoryId
			  WHERE (ProcessDefinition_Repository.RepositoryName = @repositoryName) AND
								  CONTAINS(ProcessDefinition_ProcessHistory.*, @searchFor)
			  GROUP BY ProcessDefinition_ProcessHistory.ProcessId) AS LatestFoundProcesses INNER JOIN
			  ProcessDefinition_ProcessHistory AS ProcessDefinition_ProcessHistory_1 ON LatestFoundProcesses.LatestMinorVersion = ProcessDefinition_ProcessHistory_1.MinorVersion AND LatestFoundProcesses.ProcessId = ProcessDefinition_ProcessHistory_1.ProcessId INNER JOIN
			  ProcessDefinition_Process ON LatestFoundProcesses.ProcessId = ProcessDefinition_Process.ProcessId INNER JOIN
			  ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory_1.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
	   WHERE (ProcessDefinition_Process.IsDeleted = 0) AND (ProcessDefinition_PublishProcess.PublishId = @lastPublishedId)
	   ORDER BY CASE WHEN ProcessDefinition_ProcessHistory_1.ProcessTitle = @StrippedTitle THEN 1 ELSE 2 END, ProcessDefinition_ProcessHistory_1.ProcessTitle

    END


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
PRINT N'Creating [dbo].[Search_RepositorySearchFiles]'
GO
CREATE PROCEDURE [dbo].[Search_RepositorySearchFiles] 
	@searchFor nvarchar(500),
	@repositoryName nvarchar(256),
	@userId int
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @StrippedTitle nvarchar(500)
	SET @StrippedTitle=REPLACE(@searchFor,'"','')


	DECLARE @RepositoryId int
	SET @RepositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	SELECT     UploadedFilename,UploadedFileUrlOffset, ContentSnippet
	FROM         ProcessDefinition_UploadedFile
	WHERE     (RepositoryId = @RepositoryId) AND
	(CONTAINS(ProcessDefinition_UploadedFile.*, @searchFor) OR LEFT(UploadedFilename,LEN(@StrippedTitle))=@StrippedTitle)
	ORDER BY CASE WHEN LEFT(UploadedFilename,LEN(@StrippedTitle))=@StrippedTitle THEN 1 ELSE 2 END,UploadedFilename


END
GO
IF @@ERROR <> 0 SET NOEXEC ON
PRINT N'Creating [dbo].[ProcessDefinition_GetAutocompleteProcesses]'
GO
CREATE PROCEDURE [dbo].[ProcessDefinition_GetAutocompleteProcesses]
     @repositoryName nvarchar(256),
	@Name nvarchar(128),
	@userId int,
	@usePublished bit
WITH ENCRYPTION AS
BEGIN
			SET NOCOUNT ON;

	DECLARE @repositoryId int
	SET @repositoryId=dbo.ProcessDefinition_GetRepositoryId(@repositoryName)

	DECLARE @rawSearch nvarchar(128)
	SET @rawSearch='"'+REPLACE(@Name,'%','')+'"'

	if(@usePublished=0)
	BEGIN

	    SELECT ProcessId, ProcessTitle,PrettyPostTitle,HasPostAccess FROM
	    (
		    SELECT     ProcessId, ProcessTitle,PrettyPostTitle, dbo.ProcessDefinition_HasPostAccess(PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 1 AS SortOrder
		    FROM         ProcessDefinition_Process
		    WHERE     (ProcessTitle LIKE @Name) AND (ForeignId = @repositoryId) AND IsDeleted=0
		    UNION
		    SELECT     ProcessId, ProcessTitle, PrettyPostTitle,dbo.ProcessDefinition_HasPostAccess(PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 2 AS SortOrder
		    FROM         ProcessDefinition_Process
		    WHERE CONTAINS(ProcessDefinition_Process.*,@rawSearch) AND (ForeignId = @repositoryId) AND IsDeleted=0
		    UNION
		    SELECT ProcessDefinition_Process.ProcessId, ProcessDefinition_Process.ProcessTitle, ProcessDefinition_Process.PrettyPostTitle,dbo.ProcessDefinition_HasPostAccess(ProcessDefinition_Process.PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 2 AS SortOrder
		    FROM  ProcessDefinition_Step INNER JOIN
		   ProcessDefinition_Process ON ProcessDefinition_Step.ParentProcessId = ProcessDefinition_Process.ProcessId
			WHERE CONTAINS(ProcessDefinition_Step.*,@rawSearch) AND (ProcessDefinition_Process.ForeignId = @repositoryId) AND ProcessDefinition_Process.IsDeleted=0
	    ) AS X
	    GROUP BY ProcessId, ProcessTitle,PrettyPostTitle,HasPostAccess
	    ORDER BY MIN(SortOrder),CAST(ProcessTitle AS nvarchar(128))
    END
    ELSE
    BEGIN
	   DECLARE @lastPublishedId int

	   SELECT @lastPublishedId=MAX(PublishId)
	   FROM  ProcessDefinition_Publish
	   WHERE (RepositoryId = @repositoryId)

	   SELECT ProcessId, ProcessTitle,PrettyPostTitle,HasPostAccess FROM
	    (
			 SELECT ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle, dbo.ProcessDefinition_HasPostAccess(ProcessDefinition_ProcessHistory.PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 1 AS SortOrder
			 FROM  ProcessDefinition_ProcessHistory INNER JOIN
					ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
			 WHERE (ProcessDefinition_PublishProcess.PublishId = @lastPublishedId)
    			 AND (ProcessTitle LIKE @Name) AND (ForeignId = @repositoryId) AND IsDeleted=0
		    UNION
			 SELECT ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle, dbo.ProcessDefinition_HasPostAccess(ProcessDefinition_ProcessHistory.PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 2 AS SortOrder
			 FROM  ProcessDefinition_ProcessHistory INNER JOIN
					ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
			 WHERE (ProcessDefinition_PublishProcess.PublishId = @lastPublishedId)		    
			 AND CONTAINS(ProcessDefinition_ProcessHistory.*,@rawSearch) AND (ForeignId = @repositoryId) AND IsDeleted=0
		    UNION
			 SELECT ProcessDefinition_ProcessHistory.ProcessId, ProcessDefinition_ProcessHistory.ProcessTitle, ProcessDefinition_ProcessHistory.PrettyPostTitle,dbo.ProcessDefinition_HasPostAccess(ProcessDefinition_ProcessHistory.PrettyPostTitle, @repositoryName, @userId) AS HasPostAccess, 2 AS SortOrder
			 FROM  ProcessDefinition_ProcessHistory INNER JOIN
					ProcessDefinition_StepHistory ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_StepHistory.ProcessHistoryId INNER JOIN
					ProcessDefinition_PublishProcess ON ProcessDefinition_ProcessHistory.ProcessHistoryId = ProcessDefinition_PublishProcess.ProcessHistoryId
			 WHERE (ProcessDefinition_PublishProcess.PublishId = @lastPublishedId)
						 AND CONTAINS(ProcessDefinition_StepHistory.*,@rawSearch) AND (ProcessDefinition_ProcessHistory.ForeignId = @repositoryId) AND ProcessDefinition_ProcessHistory.IsDeleted=0

	    ) AS X
	    GROUP BY ProcessId, ProcessTitle,PrettyPostTitle,HasPostAccess
	    ORDER BY MIN(SortOrder),CAST(ProcessTitle AS nvarchar(128))

    END
END
GO
IF @@ERROR <> 0 SET NOEXEC ON


BEGIN TRANSACTION

-- Add 14 rows to [dbo].[Email_EmailTemplate]
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (1, N'New user', N'Welcome to [[Site]]', N'		<p>Hello,</p><p>&nbsp;</p><p>We''ve created you an account on [[Site]].</p><p>You can sign in to your new library at:</p><p><a href="http://[[Repos]].[[Site]]">http://[[Repos]].[[Site]]</a></p><p>We''ve set&nbsp;you password to:</p><p>[[Password]]</p><p>We recommend changing this as soon as you sign in.</p><p>&nbsp;</p><p>Regards,</p><p>&nbsp;</p><p>[[Site]]</p>', N'[[Email]] [[Name]] [[Password]] [[Repos]] [[Site]]', N'[[Email]]', N'', N'support@processdefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (2, N'You''ve been added to a repository', N'New process library at [[Site]]', N'		<p>Hello [[Name]],</p><p>&nbsp;</p><p>You''ve been added to the [[Repos]] library.</p><p>&nbsp;</p><p>You can access this at <a href="http://[[Repos]].[[Site]]">http://[[Repos]].[[Site]]</a></p><p>&nbsp;</p><p>Regards,</p><p>&nbsp;</p><p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[Site]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (3, N'Forgot password', N'New [[Site]] password', N'		<p>Hello [[Name]],</p><p>&nbsp;</p><p>Here''s a new password:</p><p>[[Password]]</p><p>&nbsp;</p><p>Please remember to change it as soon as you sign in.</p><p>&nbsp;</p><p>Regards,</p><p>&nbsp;</p><p>[[Site]]</p>', N'[[Email]] [[Name]] [[Password]] [[Site]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (4, N'You''ve been added to a project', N'You''ve been added to a project', N'		<p>Hi [[Name]],</p><p>&nbsp;</p><p>You''ve been added to the <strong>[[ProjectName]] </strong>project in the&nbsp;<strong>[[Repos]]</strong> library.</p><p>&nbsp;</p><p>You can access this at <a href="http://[[Repos]].[[Site]]/">http://[[Repos]].[[Site]]</a></p><p>&nbsp;</p><p>Regards,</p><p>&nbsp;</p><p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[ProjectName]] [[Site]]', N'[[Email]]', N'', N'support@processdefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (5, N'Estimated start due notification', N'An estimated start is approaching', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The estimated start date for the [[TaskName]] task on the [[ProjectName]] project is [[EstimatedStartDate]].</p>
<p>&nbsp;</p>
<p>You can access this at <a href="http://[[RepositoryName]].[[Site]]/Project/[[ProjectId]]/Framed/[[TaskId]]">http://[[RepositoryName]].[[Site]]</a></p>
<p>&nbsp;</p>
<p>Regards,</p>
<p>&nbsp;</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[ProjectName]] [[ProjectId]] [[TaskId]]  [[TaskName]] [[EstimatedStartDate]] [[EstimatedFinishDate]] [[Site]] [[RepositoryName]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (6, N'Estimated finish date notification', N'An estimated finish date is approaching', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The estimated finish date for the [[TaskName]] task on the [[ProjectName]] project is&nbsp;[[EstimatedFinishDate]].</p>
<p>&nbsp;</p>
<p>You can access this at <a href="http://[[RepositoryName]].[[Site]]/Project/[[ProjectId]]/Framed/[[TaskId]]">http://[[RepositoryName]].[[Site]]</a></p>
<p>&nbsp;</p>
<p>Regards,</p>
<p>&nbsp;</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[ProjectName]] [[ProjectId]] [[TaskId]]  [[TaskName]] [[EstimatedStartDate]] [[EstimatedFinishDate]] [[Site]] [[RepositoryName]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (7, N'Assigned task', N'You have been assigned a task', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The [[TaskName]] task on the [[ProjectName]] project has been assigned to you with the following information:<br />[[AssignmentNote]]<br /></p>
<p>You can access the task at <a href="http://[[Repos]].[[Site]]/Project/[[ProjectId]]/Framed/[[TaskId]]">http://[[Repos]].[[Site]]/Project/[[ProjectId]]/Framed/[[TaskId]]</a><br /></p>
<p>Regards,</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[ProjectName]] [[ProjectId]] [[TaskId]] [[TaskName]] [[AssignmentNote]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (8, N'Removed assigned task', N'You have been removed from a task', N'
		<p>Hi [[Name]],<br /></p>
<p>Your assignment to the [[TaskName]] task on the [[ProjectName]] project has been removed.<br /><br />Regards,</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[ProjectName]] [[ProjectId]] [[TaskId]] [[TaskName]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (9, N'Comment to author', N'A comment has been posted on a process you last edited', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The following comment on&nbsp;the&nbsp;process [[ProcessName]] you last edited has been posted:<br />[[Comment]]<br /><br /></p>
<p>You can access the process at <a href="http://[[Repos]].[[Site]]/[[ProcessUrl]]">http://[[Repos]].[[Site]]/[[ProcessUrl]]</a><br /></p>
<p>Regards,</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[Site]] [[ProcessName]] [[ProcessUrl]] [[Comment]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (10, N'Comment posted', N'A comment has been postedon a process you have previously discussed', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The following comment on&nbsp;the&nbsp;process [[ProcessName]] you have previously commented on has been posted:<br />[[Comment]]<br /><br /></p>
<p>You can access the process at <a href="http://[[Repos]].[[Site]]/[[ProcessUrl]]">http://[[Repos]].[[Site]]/[[ProcessUrl]]</a><br /></p>
<p>Regards,</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Repos]] [[Site]] [[ProcessName]] [[ProcessUrl]] [[Comment]]', N'[[Email]]', N'', N'support@processDefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (11, N'Task can start', N'A project task is ready to start', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>The [[TaskName]] task on the [[ProjectName]] project can now be started.</p>
<p>&nbsp;</p>
<p>You can access this at <a href="http://[[RepositoryName]].[[Site]]/Project/[[ProjectId]]/Framed/[[TaskId]]">http://[[RepositoryName]].[[Site]]</a></p>
<p>&nbsp;</p>
<p>Regards,</p>
<p>&nbsp;</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[ProjectName]] [[ProjectId]] [[TaskId]]  [[TaskName]] [[EstimatedStartDate]] [[EstimatedFinishDate]] [[Site]] [[RepositoryName]]', N'[[Email]]', N'', N'support@devProcess.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (12, N'New site admin', N'Welcome to process director', N'
		<p>Hello,</p>
<p>&nbsp;</p>
<p>We''ve created you a site administrator&nbsp;account on [[Site]].</p>
<p>You can sign in to at:</p>
<p><a href="http://[[Repos]].[[Site]]">http://[[Site]]</a></p>
<p>We''ve set&nbsp;you password to:</p>
<p>[[Password]]</p>
<p>We recommend changing this as soon as you sign in.</p>
<p>&nbsp;</p>
<p>Regards,</p>
<p>&nbsp;</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Password]] [[Site]]', N'[[Email]]', N'', N'support@processdefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (13, N'You are now a site admin', N'You have been promoted to a site administrator', N'
		<p>Hello,</p>
<p><br /><br />You have been promoted to a site administrator on [[Site]].</p>
<p>You can sign in to at:</p>
<p><a href="http://[[Repos]].[[Site]]">http://[[Site]]</a><br /></p>
<p>Regards,</p>
<p>&nbsp;</p>
<p>[[Site]]</p>', N'[[Email]] [[Name]] [[Site]]', N'[[Email]]', N'', N'support@processdefinition.com', N'', N'')
INSERT INTO [dbo].[Email_EmailTemplate] ([EmailTemplateId], [TemplateName], [EmailSubject], [EmailBody], [SubstitutionsAvailable], [ToAddress], [CcAddress], [FromAddress], [BccAddress], [ReadReceipt]) VALUES (14, N'Assigned role', N'You have been assigned to a project role', N'
		<p>Hi [[Name]],</p>
<p>&nbsp;</p>
<p>You have been assigned the [[RoleName]] role on the [[ProjectName]] project with the following information:<br />[[AssignmentNote]]</p>
<p><br />You can access the project at <a href="http://[[Repos]].[[Site]]/Project/[[ProjectId]]/Home">http://[[Repos]].[[Site]]/Project/[[ProjectId]]/Home</a></p>
<p><br />Regards,</p>
<p>[[Site]]</p>', N'[[Email]] [[Repos]] [[Site]] [[Name]] [[ProjectName]] [[ProjectId]] [[RoleName]] [[AssignmentNote]]', N'[[Email]]', N'', N'support@processdefinition.com', N'', N'')
COMMIT TRANSACTION

