USE [EnVisage]
GO

/****** Object:  View [dbo].[VW_ProjectAccessByUserExtended]    Script Date: 5/26/2016 10:30:12 AM ******/
if exists (select 1 from sys.all_views where name like 'VW_ProjectAccessByUserExtended')
begin
	DROP VIEW [dbo].[VW_ProjectAccessByUserExtended]
end
GO

/****** Object:  View [dbo].[VW_ProjectAccessByUserExtended]    Script Date: 5/26/2016 10:30:12 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[VW_ProjectAccessByUserExtended] AS
select P.Id, P.CompanyId, P.ClientId, P.TypeId, P.StatusId, P.Name, P.ProjectNumber, P.Color, P.Details, P.Priority, P.Probability, P.IsRevenueGenerating, P.Deadline,
	P.ParentProjectId, P.HasChildren, P.PerformanceRedThreshold, P.PerformanceYellowThreshold, P.PartNum, P.EditTimestamp, B.UserId,
	ISNULL(C.Name, '') AS StatusName, ISNULL(D.Name, '') AS CompanyName, ISNULL(E.Name, '') AS ClientName,
	ISNULL(F.Name, '') AS TypeName, G.Id AS ActiveScenarioId, ISNULL(G.Name, '') AS ActiveScenarioName,
	ISNULL(
	(
		STUFF((SELECT ',' + t.Name AS [text()]
		FROM	dbo.Team2Project	t2p
		JOIN	dbo.Team			t
		ON		t2p.TeamId		=	t.Id
		WHERE	t2p.ProjectId	=	P.Id
		ORDER BY t.Name ASC
		FOR XML PATH('')), 1, 1, '')
	), '') AS Teams,
B.[Read], B.Write 
from Project P
	INNER JOIN VW_ProjectAccessExtended B ON (B.ProjectId = P.Id)
	LEFT JOIN [Status] C ON (C.Id = P.StatusId)
	LEFT JOIN Company D ON (D.Id = P.CompanyId)
	LEFT JOIN Client E ON (E.Id = P.ClientId)
	LEFT JOIN [Type] F ON (F.Id = P.TypeId)
	LEFT JOIN Scenario G ON (G.ParentId = P.Id) AND (G.[Type] = 2) AND (G.[Status] = 1) -- Poftfolio scenario & active
WHERE (B.[Read] = 1) OR (B.Write = 1)
GO


