USE [EnVisage]
GO

if exists (select 1 from sys.views where name like 'VW_PlanningCapacityAdjusted')
begin
	DROP VIEW [dbo].[VW_PlanningCapacityAdjusted]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE VIEW [dbo].[VW_PlanningCapacityAdjusted]
AS
WITH allocations as (SELECT sc.Id as ScenarioId, HA.WeekEndingDate, 
	Min(cast(HA.Sunday as decimal)) as Sunday, Min(cast(HA.Monday as decimal)) as Monday, Min(cast(HA.Tuesday as decimal)) as Tuesday, Min(cast(HA.Wednesday as decimal)) as Wednesday, 
	Min(cast(HA.Thursday as decimal)) as Thursday, Min(cast(HA.Friday as decimal)) as Friday, Min(cast(HA.Saturday as decimal)) as Saturday
FROM Scenario sc
	inner join ScenarioDetail sd on sd.ParentID = sc.Id
	inner join Team t on t.PlannedCapacityScenarioId = sc.Id
	left join Holiday2Team H2T on t.Id = H2T.TeamId
	left join Holiday2ExpenditureCategory H2E on sd.ExpenditureCategoryId = H2E.ExpenditureCategoryId
	left join Holiday H on 
		(H.CompanyImpact = 1) -- all resources in case Company Impact is set to 'All Resources'
		OR (H.CompanyImpact = 0 AND H.IsInclude = 1 AND (H.Id = H2T.HolidayId OR H.Id = H2E.HolidayId)) -- teams from 'Teams' dropdown and expenditures from 'Expenditures' dropdown if company impact is 'Some Resources' and Include mode
		OR (H.CompanyImpact = 0 AND H.IsInclude = 0 AND H.Id <> H2T.HolidayId AND H.Id <> H2E.HolidayId) -- teams from 'Teams' dropdown and expenditures from 'Expenditures' dropdown if company impact is 'Some Resources' and Exclude mode
	left join HolidayAllocation HA on HA.HolidayId = H.Id
where H.WorkingDays = 0 and HA.WeekEndingDate IS NOT NULL
group by sc.Id, HA.WeekEndingDate)
select HA.ScenarioId, HA.WeekEndingDate,
	ISNULL (case (cast (Wk.Sunday as decimal)+cast (Wk.Monday as decimal)+cast (Wk.Tuesday as decimal)+cast (Wk.Wednesday as decimal)+cast (Wk.Thursday as decimal)+cast (Wk.Friday as decimal)+cast (Wk.Saturday as decimal))
		when 0 then 0 
		else ((cast (Wk.Sunday as decimal) * HA.Sunday)+(cast (Wk.Monday as decimal) * HA.Monday)+(cast(Wk.Tuesday as decimal) * HA.Tuesday)+(cast(Wk.Wednesday as decimal) * HA.Wednesday)+(cast(Wk.Thursday as decimal) * HA.Thursday)+(cast(Wk.Friday as decimal) * HA.Friday)+(cast(Wk.Saturday as decimal) * HA.Saturday)) / (cast(Wk.Sunday as decimal)+cast(Wk.Monday as decimal)+cast(Wk.Tuesday as decimal)+cast(Wk.Wednesday as decimal)+cast(Wk.Thursday as decimal)+cast(Wk.Friday as decimal)+cast(Wk.Saturday as decimal))
	end, 0) as AdjustmentKoeff
from allocations HA
	inner join WorkWeek Wk on Wk.Id = (select top 1 SystemWeek.Id from WorkWeek SystemWeek where SystemWeek.IsSystem = 1)
GO

select * from VW_PlanningCapacityAdjusted