-- SCHEMA: ob

---------------------------------------------
--  TABLES
---------------------------------------------


---------------------------------------------
-- ob.AccountVariabilityOverride ------------------
---------------------------------------------
CREATE TABLE [ob].[AccountVariabilityOverride] (
    [AccountVariabilityOverrideID] int NOT NULL,
    [DepartmentAssignment] nvarchar(800) NOT NULL,
    [AccountAssignment] nvarchar(800) NOT NULL,
    [PrecedentOrder] int NOT NULL,
    [Variability] decimal NOT NULL,
    PRIMARY KEY ([AccountVariabilityOverrideID])
);
GO
ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Depar__0EB4746A] DEFAULT ('') FOR [DepartmentAssignment]; GO
ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Accou__0FA898A3] DEFAULT ('') FOR [AccountAssignment]; GO
ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Prece__109CBCDC] DEFAULT ((0)) FOR [PrecedentOrder]; GO
ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Varia__1190E115] DEFAULT ((0)) FOR [Variability]; GO

---------------------------------------------

---------------------------------------------
-- ob.AssumptionImportHistory ------------------
---------------------------------------------
CREATE TABLE [ob].[AssumptionImportHistory] (
    [HistoryGUID] uniqueidentifier NOT NULL,
    [BudgetModelType] nvarchar(30) NOT NULL,
    [DataCategory] nvarchar(50) NOT NULL,
    [ModelSection] nvarchar(100) NOT NULL,
    [AssumptionType] nvarchar(100) NOT NULL,
    [Models] nvarchar(max) NOT NULL,
    [IsDetailedLevel] bit NULL,
    [LineItems] nvarchar(max) NOT NULL,
    [Status] tinyint NOT NULL,
    PRIMARY KEY ([HistoryGUID])
);
GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [FK_AssumptionImportHistory_SystemCenterImportHistory] FOREIGN KEY ([HistoryGUID]) REFERENCES [dbo].[SystemCenterImportHistory] ([HistoryGUID]); GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [CK_AssumptionImportHistory_Status] CHECK ([Status]=(3) OR [Status]=(2) OR [Status]=(1) OR [Status]=(0)); GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_IsDetailedLevel] DEFAULT (NULL) FOR [IsDetailedLevel]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_Status] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_BudgetModelType] DEFAULT ('') FOR [BudgetModelType]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_DataCategory] DEFAULT ('') FOR [DataCategory]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_ModelSection] DEFAULT ('') FOR [ModelSection]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_AssumptionType] DEFAULT ('') FOR [AssumptionType]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_Models] DEFAULT ('') FOR [Models]; GO
ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_LineItems] DEFAULT ('') FOR [LineItems]; GO

---------------------------------------------

---------------------------------------------
-- ob.DefaultMethodList ------------------
---------------------------------------------
CREATE TABLE [ob].[DefaultMethodList] (
    [ListID] int NOT NULL,
    [ListName] nvarchar(200) NOT NULL,
    [Template] nvarchar(100) NOT NULL,
    [IncludeGlobal] bit NOT NULL,
    [IsDynamic] bit NOT NULL,
    [DescriptionOfDynamic] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ListID])
);
GO
ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_ListName] DEFAULT ('') FOR [ListName]; GO
ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_Template] DEFAULT ('') FOR [Template]; GO
ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_IncludeGlobal] DEFAULT ((0)) FOR [IncludeGlobal]; GO
ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_IsDynamic] DEFAULT ((0)) FOR [IsDynamic]; GO
ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_DescriptionOfDynamic] DEFAULT ('') FOR [DescriptionOfDynamic]; GO

---------------------------------------------

---------------------------------------------
-- ob.DefaultMethodListItem ------------------
---------------------------------------------
CREATE TABLE [ob].[DefaultMethodListItem] (
    [ListItemID] int NOT NULL,
    [ListItemName] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [ListID] int NOT NULL,
    [IsDynamic] bit NOT NULL,
    [DescriptionOfDynamic] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ListItemID])
);
GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [FK__DefaultMe__ListI__561CDE04] FOREIGN KEY ([ListID]) REFERENCES [ob].[DefaultMethodList] ([ListID]); GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_ListItemName] DEFAULT ('') FOR [ListItemName]; GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_ListID] DEFAULT ((0)) FOR [ListID]; GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_IsDynamic] DEFAULT ((0)) FOR [IsDynamic]; GO
ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_DescriptionOfDynamic] DEFAULT ('') FOR [DescriptionOfDynamic]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimAccountPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimAccountPH] (
    [AccountPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([AccountPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimAccountPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimAccoun__Histo__0EF1A5F3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimOBAccou__Name__1B351F42] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__OB_DimAccountPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimOBAcco__Membe__1C29437B] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimAdjustmentCategory ------------------
---------------------------------------------
CREATE TABLE [ob].[DimAdjustmentCategory] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [AdjustmentCategoryID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [AdjustmentCategoryRollup] nvarchar(200) NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([AdjustmentCategoryID])
);
GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Budge__2405942C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjustm__Name__21292781] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Descr__221D4BBA] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Adjus__23116FF3] DEFAULT ('') FOR [AdjustmentCategoryRollup]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Trans__24F9B865] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Membe__25EDDC9E] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Histo__1F40DF0F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimDepartmentalBudget ------------------
---------------------------------------------
CREATE TABLE [ob].[DimDepartmentalBudget] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [Name] nvarchar(458) NOT NULL,
    [DepartmentID] int NOT NULL,
    [DepartmentName] nvarchar(203) NOT NULL,
    [SystemID] smallint NOT NULL,
    [System] nvarchar(100) NOT NULL,
    [EntityID] int NOT NULL,
    [Entity] nvarchar(100) NOT NULL,
    [DepartmentRollup1ID] smallint NOT NULL,
    [DepartmentRollup1] nvarchar(100) NOT NULL,
    [DepartmentRollup2ID] smallint NOT NULL,
    [DepartmentRollup2] nvarchar(100) NOT NULL,
    [DepartmentRollup3ID] smallint NOT NULL,
    [DepartmentRollup3] nvarchar(100) NOT NULL,
    [DepartmentRollup4ID] int NOT NULL,
    [DepartmentRollup4] nvarchar(100) NOT NULL,
    [DepartmentRollup5ID] smallint NOT NULL,
    [DepartmentRollup5] nvarchar(100) NOT NULL,
    [DepartmentRollup6ID] smallint NOT NULL,
    [DepartmentRollup6] nvarchar(100) NOT NULL,
    [ResearchDepartmentCategoryID] int NOT NULL,
    [ResearchDepartmentCategoryName] nvarchar(100) NOT NULL,
    [Admin] nvarchar(400) NOT NULL,
    [Finance] nvarchar(400) NOT NULL,
    [VicePresident] nvarchar(400) NOT NULL,
    [Director] nvarchar(400) NOT NULL,
    [Manager] nvarchar(400) NOT NULL,
    [BaseYear] float NOT NULL,
    [BaseYear1] float NOT NULL,
    [StartYear] float NOT NULL,
    [NumberofYears] float NOT NULL,
    [MonthsLoaded] nvarchar(200) NOT NULL,
    [OBActivePlans] nvarchar(200) NOT NULL,
    [BudgetStatus] nvarchar(100) NOT NULL,
    [OpenDate] date NOT NULL,
    [LastModified] nvarchar(200) NOT NULL,
    [WorkedHrsperUOSProjection] float NOT NULL,
    [WorkedHrsperUOSBudget] float NOT NULL,
    [FTEApprovalOverride] nvarchar(100) NOT NULL,
    [FrameworkID] int NOT NULL,
    [LootID] int NOT NULL,
    [HourTypeFixed] nvarchar(200) NOT NULL,
    [HourType] nvarchar(200) NOT NULL,
    [TargetType] nvarchar(200) NOT NULL,
    [IsVariable] bit NOT NULL,
    [VariableProjectionMethod] nvarchar(200) NOT NULL,
    [ContractLaborSkillMix] nvarchar(200) NOT NULL,
    [EntitySortOrder] int NOT NULL,
    [SystemSortOrder] int NOT NULL,
    [DepartmentRollup1SortOrder] int NOT NULL,
    [DepartmentRollup2SortOrder] int NOT NULL,
    [DepartmentRollup3SortOrder] int NOT NULL,
    [DepartmentRollup4SortOrder] int NOT NULL,
    [DepartmentRollup5SortOrder] int NOT NULL,
    [DepartmentRollup6SortOrder] int NOT NULL,
    [ResearchDepartmentCategorySortOrder] int NOT NULL,
    [HasAttachments] nvarchar(200) NOT NULL,
    [HideNotSpecified] nvarchar(400) NOT NULL,
    [GMTestFWName] nvarchar(450) NOT NULL,
    [GMTestFWDateCreated] nvarchar(200) NOT NULL,
    [TransactionID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [MRVicePresident] nvarchar(400) NOT NULL,
    [MRDirector] nvarchar(400) NOT NULL,
    [MRManager] nvarchar(400) NOT NULL,
    [ReadOnly] nvarchar(400) NOT NULL,
    [WriteDeny] nvarchar(400) NOT NULL,
    [EntityDefaultWorkWeekID] int NOT NULL,
    [OBDirector] nvarchar(400) NOT NULL,
    [OBManager] nvarchar(400) NOT NULL,
    [OBVicePresident] nvarchar(400) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [DepartmentCode] nvarchar(100) NOT NULL,
    [VariablehrsperUOSActualYTD] float NOT NULL,
    [VariablehrsperUOStargetCurrentYr] float NOT NULL,
    [VariablehrsperUOS] float NOT NULL,
    [VariablehrsperUOStarget] float NOT NULL,
    [BudgetedFixedFTEs] float NOT NULL,
    [BudgetedVariableFTEs] float NOT NULL,
    [UOSchangeyy] float NOT NULL,
    [ExcessofRevandExpchangeyy] float NOT NULL,
    PRIMARY KEY ([DepartmentalBudgetID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_DepartmentID] ON [ob].[DimDepartmentalBudget] ([DepartmentID]);
CREATE NONCLUSTERED INDEX [IX_DepartmentalBudgetID] ON [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]);
CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [ob].[DimDepartmentalBudget] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__11ECDB15] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBAct__7DF62CF7] DEFAULT ('') FOR [OBActivePlans]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__068B72F8] DEFAULT ('Draft') FOR [BudgetStatus]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OpenD__7EEA5130] DEFAULT ('') FOR [OpenDate]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__LastM__7B19C04C] DEFAULT ('') FOR [LastModified]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Worke__077F9731] DEFAULT ((0)) FOR [WorkedHrsperUOSProjection]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Worke__0873BB6A] DEFAULT ((0)) FOR [WorkedHrsperUOSBudget]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__FTEAp__0B502815] DEFAULT ('None') FOR [FTEApprovalOverride]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Frame__0C3401BF] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__LootI__0E1C4A31] DEFAULT ((0)) FOR [LootID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HourT__71591BAD] DEFAULT ('') FOR [HourTypeFixed]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HourT__4F20D1DE] DEFAULT ('') FOR [HourType]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Secur__64849E34] DEFAULT ((0)) FOR [SecureGroupID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Targe__03C9A447] DEFAULT ('') FOR [TargetType]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__IsVar__6CB396CA] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__06A610F2] DEFAULT ('') FOR [VariableProjectionMethod]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Contr__05B1ECB9] DEFAULT ('') FOR [ContractLaborSkillMix]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__486CE00A] DEFAULT ((0)) FOR [EntitySortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__49610443] DEFAULT ((0)) FOR [SystemSortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBDir__6A46CDD4] DEFAULT ('') FOR [OBDirector]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4A55287C] DEFAULT ((0)) FOR [DepartmentRollup1SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBMan__6B3AF20D] DEFAULT ('') FOR [OBManager]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4B494CB5] DEFAULT ((0)) FOR [DepartmentRollup2SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBVic__6C2F1646] DEFAULT ('') FOR [OBVicePresident]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4C3D70EE] DEFAULT ((0)) FOR [DepartmentRollup3SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4D319527] DEFAULT ((0)) FOR [DepartmentRollup4SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4E25B960] DEFAULT ((0)) FOR [DepartmentRollup5SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4F19DD99] DEFAULT ((0)) FOR [DepartmentRollup6SortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__43A82AED] DEFAULT ((0)) FOR [ResearchDepartmentCategorySortOrder]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HasAt__7A259C13] DEFAULT ('') FOR [HasAttachments]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HideN__1F9F094A] DEFAULT ('') FOR [HideNotSpecified]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__GMTes__6A243E74] DEFAULT ('') FOR [GMTestFWName]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__GMTes__6B1862AD] DEFAULT ('') FOR [GMTestFWDateCreated]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRVic__74A1FEB1] DEFAULT ('') FOR [MRVicePresident]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__OB_DimDepartmentalBudget_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRDir__7966B3CE] DEFAULT ('') FOR [MRDirector]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRMan__7E2B68EB] DEFAULT ('') FOR [MRManager]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__ReadO__03101999] DEFAULT ('') FOR [ReadOnly]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Write__04043DD2] DEFAULT ('') FOR [WriteDeny]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_DimOBPlan_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__2B61FAC8] DEFAULT ('') FOR [DepartmentCode]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2C1889E4] DEFAULT ((0)) FOR [VariablehrsperUOSActualYTD]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2D0CAE1D] DEFAULT ((0)) FOR [VariablehrsperUOStargetCurrentYr]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2E00D256] DEFAULT ((0)) FOR [VariablehrsperUOS]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2EF4F68F] DEFAULT ((0)) FOR [VariablehrsperUOStarget]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__2FE91AC8] DEFAULT ((0)) FOR [BudgetedFixedFTEs]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__30DD3F01] DEFAULT ((0)) FOR [BudgetedVariableFTEs]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__UOSch__31D1633A] DEFAULT ((0)) FOR [UOSchangeyy]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Exces__32C58773] DEFAULT ((0)) FOR [ExcessofRevandExpchangeyy]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_OBDIMDEPARTMENTALBUDGETMEMBERGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepartm__Name__0D2825F8] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_DimDepartmentalBudget_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__0F106E6A] DEFAULT ('') FOR [DepartmentName]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__100492A3] DEFAULT ((0)) FOR [SystemID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__10F8B6DC] DEFAULT ('') FOR [System]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__12E0FF4E] DEFAULT ('') FOR [Entity]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__13D52387] DEFAULT ((0)) FOR [DepartmentRollup1ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__14C947C0] DEFAULT ('') FOR [DepartmentRollup1]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__15BD6BF9] DEFAULT ((0)) FOR [DepartmentRollup2ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__16B19032] DEFAULT ('') FOR [DepartmentRollup2]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__17A5B46B] DEFAULT ((0)) FOR [DepartmentRollup3ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1899D8A4] DEFAULT ('') FOR [DepartmentRollup3]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__489A2A98] DEFAULT ((0)) FOR [EntityDefaultWorkWeekID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__198DFCDD] DEFAULT ((0)) FOR [DepartmentRollup4ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1A822116] DEFAULT ('') FOR [DepartmentRollup4]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1B76454F] DEFAULT ((0)) FOR [DepartmentRollup5ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1C6A6988] DEFAULT ('') FOR [DepartmentRollup5]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1D5E8DC1] DEFAULT ((0)) FOR [DepartmentRollup6ID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1E52B1FA] DEFAULT ('') FOR [DepartmentRollup6]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__41BFE27B] DEFAULT ((0)) FOR [ResearchDepartmentCategoryID]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__42B406B4] DEFAULT ('') FOR [ResearchDepartmentCategoryName]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Admin__1DB6C0D8] DEFAULT ('') FOR [Admin]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Finan__1EAAE511] DEFAULT ('') FOR [Finance]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__ViceP__00D299A2] DEFAULT ('') FOR [VicePresident]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Direc__783D53A1] DEFAULT ('') FOR [Director]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Manag__7C0DE485] DEFAULT ('') FOR [Manager]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__BaseY__76550B2F] DEFAULT ((0)) FOR [BaseYear]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__BaseY__05974EBF] DEFAULT ((0)) FOR [BaseYear1]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Start__09179DF2] DEFAULT ((0)) FOR [StartYear]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Numbe__0A0BC22B] DEFAULT ((3)) FOR [NumberofYears]; GO
ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Month__7D0208BE] DEFAULT ('') FOR [MonthsLoaded]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimDepartmentalBudgetPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimDepartmentalBudgetPH] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [DepartmentalBudgetPHID] tinyint NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [IsConstant] bit NOT NULL,
    [Version] timestamp NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([DepartmentalBudgetPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimDepartmentalBudgetPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_IsConstant] DEFAULT ((0)) FOR [IsConstant]; GO
ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF__OB_DimDepartmentalBudgetPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_OBDIMDEPARTMENTALBUDGETPHNAME] DEFAULT ('') FOR [Name]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimFinancialReporting ------------------
---------------------------------------------
CREATE TABLE [ob].[DimFinancialReporting] (
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Statement] nvarchar(100) NOT NULL,
    [Section] nvarchar(100) NOT NULL,
    [LineName] nvarchar(100) NOT NULL,
    [IsMappable] nvarchar(100) NOT NULL,
    [ConsolidatedFinancialReportingID] int NOT NULL,
    [ConsolidatedIsInverted] bit NOT NULL,
    [ConsolidatedInversion] int NOT NULL,
    [Name] varchar(4000) NOT NULL,
    [StatementMappabilityFilterParameter] varchar(4000) NOT NULL,
    [ConsolidatedFinancialReporting] varchar(4000) NOT NULL,
    [ConsolidatedFinancialReportingSortOrder] int NOT NULL,
    [IsExpense] bit NOT NULL,
    [IsRequired] bit NOT NULL,
    [IsVolume] bit NOT NULL,
    [IsFTERollup] bit NOT NULL,
    [IsEditable] bit NOT NULL,
    [DisplayFormat] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [ProjectionMethod] nvarchar(100) NOT NULL,
    [SpreadMethod] nvarchar(100) NOT NULL,
    [ToBeDeleted] bit NOT NULL,
    PRIMARY KEY ([FinancialReportingID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimFinancialReporting] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Finan__012DFA15] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanci__Name__1FB3E619] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__State__20A80A52] DEFAULT ('') FOR [StatementMappabilityFilterParameter]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__219C2E8B] DEFAULT ('') FOR [ConsolidatedFinancialReporting]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__229052C4] DEFAULT ((0)) FOR [ConsolidatedFinancialReportingSortOrder]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsExp__68303DB3] DEFAULT ((0)) FOR [IsExpense]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsReq__41D8B7FD] DEFAULT ((0)) FOR [IsRequired]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsVol__42CCDC36] DEFAULT ((0)) FOR [IsVolume]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsFTE__43C1006F] DEFAULT ((0)) FOR [IsFTERollup]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsEdi__44B524A8] DEFAULT ((1)) FOR [IsEditable]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Displ__57E03511] DEFAULT ('') FOR [DisplayFormat]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__ToBeD__28645F72] DEFAULT ((0)) FOR [ToBeDeleted]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__SortO__2A045BC8] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Proje__66A68310] DEFAULT ('Annualized') FOR [ProjectionMethod]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Sprea__679AA749] DEFAULT ('Projected') FOR [SpreadMethod]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Membe__7D5ECE15] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__State__7F471687] DEFAULT ('') FOR [Statement]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Secti__003B3AC0] DEFAULT ('') FOR [Section]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Histo__7E52F24E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__LineN__012F5EF9] DEFAULT ('') FOR [LineName]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsMap__0317A76B] DEFAULT ('') FOR [IsMappable]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__040BCBA4] DEFAULT ((0)) FOR [ConsolidatedFinancialReportingID]; GO
ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__04FFEFDD] DEFAULT ((0)) FOR [ConsolidatedIsInverted]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimFinancialReportingPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimFinancialReportingPH] (
    [FinancialReportingPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FinancialReportingPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimFinancialReportingPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanci__Name__171EA018] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanc__Membe__1812C451] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanc__Histo__1906E88A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimGlobalStatisticRollup ------------------
---------------------------------------------
CREATE TABLE [ob].[DimGlobalStatisticRollup] (
    [StatisticRollupID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([StatisticRollupID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimGlobalStatisticRollup] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__DimStatist__Name__1823A86D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__OB_DimGlobalStatisticRollup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__DimStatis__Membe__1917CCA6] DEFAULT (newid()) FOR [MemberGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimGlobalStatisticsPlanPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimGlobalStatisticsPlanPH] (
    [OBGlobalStatsPlanPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([OBGlobalStatsPlanPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimGlobalStatisticsPlanPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__OB_DimGlobalStatisticsPlanPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGloba__Name__37082240] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGlob__Membe__37FC4679] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGlob__Histo__38F06AB2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBAllocation ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBAllocation] (
    [OBAllocationID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Type] nvarchar(100) NOT NULL,
    [AlwaysUseBasis] bit NOT NULL,
    [OBAllocationBasisID] int NOT NULL,
    [ExecutionOrder] smallint NOT NULL,
    PRIMARY KEY ([OBAllocationID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBAllocation] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAlloc__Name__4679AAA0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Membe__476DCED9] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Trans__4956174B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAlloc__Type__4A4A3B84] DEFAULT ('') FOR [Type]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Histo__4861F312] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Alway__60397CA3] DEFAULT ((0)) FOR [AlwaysUseBasis]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Alloc__70F9F451] DEFAULT ((0)) FOR [OBAllocationBasisID]; GO
ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Execu__7BC101FA] DEFAULT ((0)) FOR [ExecutionOrder]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBAllocationBasis ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBAllocationBasis] (
    [OBAllocationBasisID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    PRIMARY KEY ([OBAllocationBasisID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBAllocationBasis] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__OBFor__1149F5AE] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Histo__667C65DE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAlloc__Name__64941D6C] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Membe__658841A5] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Trans__67708A17] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Categ__6864AE50] DEFAULT ('Not Specified') FOR [Category]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBExceptions ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBExceptions] (
    [OBExceptionsID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Severity] nvarchar(100) NOT NULL,
    [Model] nvarchar(100) NOT NULL,
    [ViewName] nvarchar(100) NOT NULL,
    [SortOrder] smallint NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [Resolution] nvarchar(max) NOT NULL,
    [FullName] nvarchar(303) NOT NULL,
    [CustomActionGUID] uniqueidentifier NOT NULL,
    [SystemCenterLink] nvarchar(400) NOT NULL,
    [IsClientException] bit NOT NULL,
    PRIMARY KEY ([OBExceptionsID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBExceptions] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_SystemCenterLink] DEFAULT ('') FOR [SystemCenterLink]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_IsClientException] DEFAULT ((1)) FOR [IsClientException]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Descr__21A8E3FB] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Resol__229D0834] DEFAULT ('') FOR [Resolution]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Histo__68C30A55] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_CustomActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomActionGUID]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExcep__Name__66DAC1E3] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Membe__67CEE61C] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Trans__69B72E8E] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Sever__6AAB52C7] DEFAULT ('') FOR [Severity]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Model__6B9F7700] DEFAULT ('') FOR [Model]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__ViewN__6C939B39] DEFAULT ('') FOR [ViewName]; GO
ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__SortO__6D87BF72] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBForecastDetail ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBForecastDetail] (
    [OBForecastDetailID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [DriverID] int NOT NULL,
    [IsSalaryDriver] bit NOT NULL,
    [IsRevenueDriver] bit NOT NULL,
    [AccountID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    [SortOrder] int NOT NULL,
    [SecondaryAccountID] int NOT NULL,
    [UnitType] nvarchar(200) NOT NULL,
    [Driver] nvarchar(200) NOT NULL,
    [Account] nvarchar(103) NOT NULL,
    [SecondaryAccount] nvarchar(103) NOT NULL,
    [Code] nvarchar(100) NOT NULL,
    [ForecastDetailRollup] nvarchar(200) NOT NULL,
    [VolumeTarget] nvarchar(200) NOT NULL,
    [IsMROnly] bit NOT NULL,
    [IsVariable] bit NOT NULL,
    PRIMARY KEY ([OBForecastDetailID])
);
GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Histo__2D11D9EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Accou__2322540F] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBForec__Code__27B46107] DEFAULT ('') FOR [Code]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Volum__2821092A] DEFAULT ('Not Specified') FOR [VolumeTarget]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBForec__Name__2B299178] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Membe__2C1DB5B1] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Trans__2E05FE23] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Categ__2EFA225C] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Drive__3F7B6E3F] DEFAULT ((0)) FOR [DriverID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsMRO__421912B3] DEFAULT ((0)) FOR [IsMROnly]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__SortO__45ED38B6] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsVar__46CA4FE5] DEFAULT ((0)) FOR [IsVariable]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Forec__4B697A10] DEFAULT ('Not Specified') FOR [ForecastDetailRollup]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsSal__56DEC1DB] DEFAULT ((0)) FOR [IsSalaryDriver]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsRev__57D2E614] DEFAULT ((0)) FOR [IsRevenueDriver]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__UnitT__6AFDF67D] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Secon__6E6609BB] DEFAULT ((0)) FOR [SecondaryAccountID]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__UnitT__6F5A2DF4] DEFAULT ('') FOR [UnitType]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Drive__704E522D] DEFAULT ('') FOR [Driver]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Accou__71427666] DEFAULT ('') FOR [Account]; GO
ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Secon__72369A9F] DEFAULT ('') FOR [SecondaryAccount]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBForecastDetailPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBForecastDetailPH] (
    [OBForecastDetailPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([OBForecastDetailPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBForecastDetailPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBForec__Name__021D5A44] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Membe__03117E7D] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Trans__04F9C6EF] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Histo__0405A2B6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBGlobalStatistics ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBGlobalStatistics] (
    [OBGlobalStatisticID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [AccountDescription] nvarchar(100) NOT NULL,
    [AccountCode] nvarchar(100) NOT NULL,
    [DepartmentCode] nvarchar(100) NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [Account] nvarchar(103) NOT NULL,
    [Department] nvarchar(203) NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [LOSLinkID] int NOT NULL,
    [OBForecastDetail] nvarchar(200) NOT NULL,
    [LOSLink] nvarchar(103) NOT NULL,
    [PatientClass] nvarchar(100) NOT NULL,
    [OBPayor] nvarchar(100) NOT NULL,
    [OBPayorGroup] nvarchar(100) NOT NULL,
    [OBUnitsFinancialReportingName] varchar(200) NOT NULL,
    [OBUnitsFinancialReportingLineName] nvarchar(100) NOT NULL,
    [FillinSection] nvarchar(120) NOT NULL,
    [Name] nvarchar(304) NOT NULL,
    PRIMARY KEY ([OBGlobalStatisticID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_AccountID_DepartmentID] ON [ob].[DimOBGlobalStatistics] ([DepartmentID], [AccountID]);
CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatistics] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Patie__0AB9C654] DEFAULT ('') FOR [PatientClass]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBPay__0BADEA8D] DEFAULT ('') FOR [OBPayor]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBPay__0CA20EC6] DEFAULT ('') FOR [OBPayorGroup]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBUni__0D9632FF] DEFAULT ('') FOR [OBUnitsFinancialReportingName]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Histo__15646D8B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBUni__0E8A5738] DEFAULT ('') FOR [OBUnitsFinancialReportingLineName]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1272F247] DEFAULT ('') FOR [Account]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__13671680] DEFAULT ('') FOR [Department]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Membe__14704952] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Trans__165891C4] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1B1D46E1] DEFAULT ('') FOR [AccountDescription]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1C116B1A] DEFAULT ('') FOR [AccountCode]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__1D058F53] DEFAULT ('') FOR [DepartmentCode]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__20D62037] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__21CA4470] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBFor__33BED779] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__LOSLi__34B2FBB2] DEFAULT ((0)) FOR [LOSLinkID]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBFor__7498769D] DEFAULT ('') FOR [OBForecastDetail]; GO
ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__LOSLi__758C9AD6] DEFAULT ('') FOR [LOSLink]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBGlobalStatisticsPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBGlobalStatisticsPH] (
    [OBGlobalStatisticsPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([OBGlobalStatisticsPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatisticsPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGloba__Name__296B6638] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Membe__2A5F8A71] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Trans__2C47D2E3] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Histo__2B53AEAA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBGlobalStatisticsPlan ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBGlobalStatisticsPlan] (
    [OBGlobalStatisticsPlanID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Name] nvarchar(1000) NOT NULL,
    [BaseYear] float NOT NULL,
    [MonthsLoaded] float NOT NULL,
    [EntityID] int NOT NULL,
    [SecureGroupID] int NOT NULL,
    [StartYear] float NOT NULL,
    [NumberofYears] float NOT NULL,
    [Entity] nvarchar(100) NOT NULL,
    [LootID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [FrameworkID] int NOT NULL,
    PRIMARY KEY ([OBGlobalStatisticsPlanID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatisticsPlan] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Membe__080A726D] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Trans__09F2BADF] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Start__1489509E] DEFAULT ((0)) FOR [StartYear]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Numbe__157D74D7] DEFAULT ((3)) FOR [NumberofYears]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Entit__23176717] DEFAULT ('') FOR [Entity]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Entit__76EAD363] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__LootI__240B8B50] DEFAULT ((0)) FOR [LootID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__IsDel__24FFAF89] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Histo__08FE96A6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF_OBDIMOBGLOBALSTATISTICSPLANSECUREGROUPID] DEFAULT ((2)) FOR [SecureGroupID]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGloba__Name__5569E407] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__BaseY__5DFF2A08] DEFAULT ((0)) FOR [BaseYear]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Month__61CFBAEC] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Frame__6578C26D] DEFAULT ((0)) FOR [FrameworkID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBReimbursementPlan ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBReimbursementPlan] (
    [OBReimbursementPlanID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [FrameworkID] tinyint NOT NULL,
    [TransactionID] int NOT NULL,
    [NameCalc] nvarchar(450) NOT NULL,
    [BaseYear] float NOT NULL,
    [EntityID] int NOT NULL,
    [StartYear] nvarchar(200) NOT NULL,
    [NumberofYears] float NOT NULL,
    [LootID] int NOT NULL,
    [Entity] nvarchar(100) NOT NULL,
    [EntitySortOrder] int NOT NULL,
    [Name] nvarchar(1000) NOT NULL,
    [SecureGroupID] int NOT NULL,
    [MonthsLoaded] nvarchar(400) NOT NULL,
    PRIMARY KEY ([OBReimbursementPlanID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBReimbursementPlan] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Start__1E12BAD8] DEFAULT ('') FOR [StartYear]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Numbe__1F06DF11] DEFAULT ((3)) FOR [NumberofYears]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__NameN__22F836DD] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Membe__28BD620F] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__LootI__29C464A6] DEFAULT ((0)) FOR [LootID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__2AB888DF] DEFAULT ('') FOR [Entity]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__2BACAD18] DEFAULT ((0)) FOR [EntitySortOrder]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Frame__2E763B65] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__OB_DimOBReimbursementPlan_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Secur__38FD51EC] DEFAULT ((0)) FOR [SecureGroupID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__16F0BBFD] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Histo__29B18648] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__NameC__72B98475] DEFAULT ('New Plan') FOR [NameCalc]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__BaseY__73ADA8AE] DEFAULT ((0)) FOR [BaseYear]; GO
ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Month__7EFC6437] DEFAULT ('') FOR [MonthsLoaded]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBReimbursementPlanPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBReimbursementPlanPH] (
    [OBReimbursementPlanPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([OBReimbursementPlanPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBReimbursementPlanPH] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReimb__Name__1D4BAF63] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReim__Membe__1E3FD39C] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__OB_DimOBReimbursementPlanPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReim__Histo__1F33F7D5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBServiceLinePlan ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBServiceLinePlan] (
    [OBServiceLinePlanID] int NOT NULL,
    [EntityID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [BaseYear] nvarchar(200) NOT NULL,
    [MonthsLoaded] nvarchar(200) NOT NULL,
    [StartYear] float NOT NULL,
    [NumberofYears] float NOT NULL,
    [FrameworkID] int NOT NULL,
    [LootID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [Entity] nvarchar(100) NOT NULL,
    [EntitySortOrder] int NOT NULL,
    [SecureGroupID] int NOT NULL,
    [Name] nvarchar(1000) NOT NULL,
    [OtherVolumeBudgetYear] float NOT NULL,
    [OutpatientVolumeProjectedYear] float NOT NULL,
    [OutpatientVolumeBudgetYear] float NOT NULL,
    [ObservationVolumeBudgetYear] float NOT NULL,
    [EDVolumeProjectedYear] float NOT NULL,
    [ObservationVolumeProjectedYear] float NOT NULL,
    [EDVolumeBudgetYear] float NOT NULL,
    [InpatientVolumeBudgetYear] float NOT NULL,
    [ClinicVolumeBudgetYear] float NOT NULL,
    [OtherVolumeProjectedYear] float NOT NULL,
    [ClinicVolumeProjectedYear] float NOT NULL,
    [InpatientVolumeProjectedYear] float NOT NULL,
    PRIMARY KEY ([OBServiceLinePlanID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBServiceLinePlan] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Histo__159BD9BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Membe__14A7B581] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Trans__168FFDF3] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Start__194E05BB] DEFAULT ((0)) FOR [StartYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Numbe__1A4229F4] DEFAULT ((3)) FOR [NumberofYears]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Frame__3165866E] DEFAULT ((0)) FOR [FrameworkID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__13B39148] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__LootI__3259AAA7] DEFAULT ((0)) FOR [LootID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__IsDel__334DCEE0] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Other__33B9ABAC] DEFAULT ((0)) FOR [OtherVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__3441F319] DEFAULT ('') FOR [Entity]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Outpa__34ADCFE5] DEFAULT ((0)) FOR [OutpatientVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__35361752] DEFAULT ((0)) FOR [EntitySortOrder]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Outpa__35A1F41E] DEFAULT ((0)) FOR [OutpatientVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Secur__362A3B8B] DEFAULT ((0)) FOR [SecureGroupID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Obser__36961857] DEFAULT ((0)) FOR [ObservationVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__EDVol__378A3C90] DEFAULT ((0)) FOR [EDVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Obser__387E60C9] DEFAULT ((0)) FOR [ObservationVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__EDVol__39728502] DEFAULT ((0)) FOR [EDVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Inpat__3A66A93B] DEFAULT ((0)) FOR [InpatientVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Clini__3B5ACD74] DEFAULT ((0)) FOR [ClinicVolumeBudgetYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Other__3C4EF1AD] DEFAULT ((0)) FOR [OtherVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Clini__3D4315E6] DEFAULT ((0)) FOR [ClinicVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__NameN__3DAC2D19] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Inpat__3E373A1F] DEFAULT ((0)) FOR [InpatientVolumeProjectedYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__BaseY__426E8031] DEFAULT ('') FOR [BaseYear]; GO
ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Month__4362A46A] DEFAULT ('') FOR [MonthsLoaded]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBServiceLinePlanPH ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBServiceLinePlanPH] (
    [OBServiceLinePlanPHID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([OBServiceLinePlanPHID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBServiceLinePlanPH] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [ob].[DimOBServiceLinePlanPH] ([Name]);
GO
ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServi__Name__41262194] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Membe__421A45CD] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Trans__44028E3F] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Histo__430E6A06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimOBSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[DimOBSnapshot] (
    [OBSnapshotID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [Date] nvarchar(100) NOT NULL,
    PRIMARY KEY ([OBSnapshotID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBSnapshot] ([MemberGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [UK_DimOBSnapshot_CategoryName] ON [ob].[DimOBSnapshot] ([Category], [Name]);
GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Histo__6CE96C4B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnaps__Name__6B0123D9] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Membe__6BF54812] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Trans__6DDD9084] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Categ__6ED1B4BD] DEFAULT ('Auto') FOR [Category]; GO
ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnaps__Date__6FC5D8F6] DEFAULT ('') FOR [Date]; GO

---------------------------------------------

---------------------------------------------
-- ob.DimSpread ------------------
---------------------------------------------
CREATE TABLE [ob].[DimSpread] (
    [SpreadID] int NOT NULL,
    [Name] nvarchar(200) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    [IsBuiltIn] bit NOT NULL,
    [SortOrder] int NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    PRIMARY KEY ([SpreadID])
);

CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimSpread] ([MemberGUID]);
GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__OB_DimSpread_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__Name__36DD39B7] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__Membe__37D15DF0] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF_DimSpread_Category] DEFAULT ('') FOR [Category]; GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__IsBui__7A6BEDED] DEFAULT ((0)) FOR [IsBuiltIn]; GO
ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__SortO__7B601226] DEFAULT ((0)) FOR [SortOrder]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAccountSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAccountSnapshot] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [Total] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactAccountSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [UnitTypeID], [AccountID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactAccountSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [UnitTypeID], [AccountID], [IsDeleted], [DataTypeID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentalBudget_OBSnapshotID] ON [ob].[FactAccountSnapshot] ([DepartmentalBudgetID], [OBSnapshotID]);
GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Accou__7672D685] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__DataT__785B1EF7] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Depar__7C2BAFDB] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Fisca__7A436769] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__OBSna__7E13F84D] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__TimeC__01E48931] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__UnitT__03CCD1A3] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__TimeC__00F064F8] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__UnitT__02D8AD6A] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__14F75DA5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__04C0F5DC] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__05B51A15] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__06A93E4E] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__079D6287] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__089186C0] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0985AAF9] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0A79CF32] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0B6DF36B] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0C6217A4] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0D563BDD] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0E4A6016] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0F3E844F] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__1032A888] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Total__1126CCC1] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Yearl__121AF0FA] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccount__YTD__130F1533] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__1403396C] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__15EB81DE] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__DataT__7766FABE] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__794F4330] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Depar__7B378BA2] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__7D1FD414] DEFAULT ((0)) FOR [OBSnapshotID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAccountSubtableVarSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAccountSubtableVarSnapshot] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [AdjustmentCategoryID] int NOT NULL,
    [AssumptionID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [Comment] nvarchar(2000) NOT NULL,
    [Comment_Comment] nvarchar(max) NOT NULL,
    [Comment_Formula] nvarchar(max) NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [Total] decimal NULL,
    [Yearly] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [FK_FactAccountSubtableVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__001E04C8] DEFAULT ('') FOR [Comment_Comment]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__01122901] DEFAULT ('d') FOR [Comment_Formula]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__02064D3A] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__02FA7173] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__03EE95AC] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__04E2B9E5] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__05D6DE1E] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__06CB0257] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__07BF2690] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__08B34AC9] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__09A76F02] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0A9B933B] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0B8FB774] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0C83DBAD] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Yearl__0D77FFE6] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__0E6C241F] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__10546C91] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__0F604858] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__7D41981D] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__7E35BC56] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__7F29E08F] DEFAULT ('') FOR [Comment]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAccountVarSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAccountVarSnapshot] (
    [RowID] int NOT NULL,
    [AccountID] int NOT NULL,
    [AssumptionID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [RowNumberID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [Amount_Comment] nvarchar(max) NOT NULL,
    [Amount_Formula] nvarchar(max) NOT NULL,
    [Comment] nvarchar(2000) NOT NULL,
    [Comment_Comment] nvarchar(max) NOT NULL,
    [Comment_Formula] nvarchar(max) NOT NULL,
    [TextValue] nvarchar(2000) NOT NULL,
    [TextValue_Comment] nvarchar(max) NOT NULL,
    [TextValue_Formula] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [FK_FactAccountVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__4D9284FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__412CAE16] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__4220D24F] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__4314F688] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__44091AC1] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__44FD3EFA] DEFAULT ('') FOR [Amount_Comment]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__45F16333] DEFAULT ('d') FOR [Amount_Formula]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__46E5876C] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__47D9ABA5] DEFAULT ('') FOR [Comment_Comment]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__48CDCFDE] DEFAULT ('d') FOR [Comment_Formula]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__49C1F417] DEFAULT ('') FOR [TextValue]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__4AB61850] DEFAULT ('') FOR [TextValue_Comment]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__4BAA3C89] DEFAULT ('d') FOR [TextValue_Formula]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__4C9E60C2] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__4E86A934] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByAccount ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByAccount] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [FK_FactAssumptionByAccount_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [DF_FactAssumptionByAccount_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [DF_FactAssumptionByAccount_AccountID] DEFAULT ((0)) FOR [AccountID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByAccountFRLineNameDetail ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [FK_FactAssumptionByAccountFRLineNameDetail_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_AccountID] DEFAULT ((0)) FOR [AccountID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByAccountFRLineNameRollup ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [FK_FactAssumptionByAccountFRLineNameRollup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByChargeCode ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByChargeCode] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [FK_FactAssumptionByChargeCode_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [DF_FactAssumptionByChargeCode_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [DF_FactAssumptionByChargeCode_ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByChargeCodeRollup ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByChargeCodeRollup] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [FK_FactAssumptionByChargeCodeRollup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [DF_FactAssumptionByChargeCodeRollup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [DF_FactAssumptionByChargeCodeRollup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByJobCode ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByJobCode] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [JobCodeGroupID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [FK_FactAssumptionByJobCode_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_JobCodeGroupID] DEFAULT ((0)) FOR [JobCodeGroupID]; GO
ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByJobCodeGroup ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByJobCodeGroup] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [JobCodeGroupID] int NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [FK_FactAssumptionByJobCodeGroup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_JobCodeGroupID] DEFAULT ((0)) FOR [JobCodeGroupID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactAssumptionByPHSection ------------------
---------------------------------------------
CREATE TABLE [ob].[FactAssumptionByPHSection] (
    [RowID] int NOT NULL,
    [GlobalAssumptionGUID] uniqueidentifier NOT NULL,
    [PHSectionGUID] uniqueidentifier NOT NULL,
    [Month01] decimal NULL,
    [Month02] decimal NULL,
    [Month03] decimal NULL,
    [Month04] decimal NULL,
    [Month05] decimal NULL,
    [Month06] decimal NULL,
    [Month07] decimal NULL,
    [Month08] decimal NULL,
    [Month09] decimal NULL,
    [Month10] decimal NULL,
    [Month11] decimal NULL,
    [Month12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [FK_FactAssumptionByPHSection_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO
ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [DF_FactAssumptionByPHSection_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO
ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [DF_FactAssumptionByPHSection_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactCDMSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactCDMSnapshot] (
    [RowID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactCDMSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [PatientClassID], [UnitTypeID], [ChargeCodeID], [OBForecastDetailID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactCDMSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [PatientClassID], [UnitTypeID], [ChargeCodeID], [OBForecastDetailID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Charg__2C6FBFDA] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__DataT__2E58084C] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Depar__32289930] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Fisca__304050BE] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__OBFor__3410E1A2] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__OBSna__289F2EF6] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Patie__35F92A14] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__TimeC__37E17286] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__UnitT__2A877768] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__OBSna__27AB0ABD] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__UnitT__2993532F] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Charg__2B7B9BA1] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__DataT__2D63E413] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Fisca__2F4C2C85] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Depar__313474F7] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__OBFor__331CBD69] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Patie__350505DB] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__TimeC__36ED4E4D] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__38D596BF] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__39C9BAF8] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3ABDDF31] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3BB2036A] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3CA627A3] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3D9A4BDC] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3E8E7015] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3F82944E] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__4076B887] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__416ADCC0] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__425F00F9] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__43532532] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Yearl__4447496B] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSnap__YTD__453B6DA4] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Total__462F91DD] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__IsDel__4723B616] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Trans__490BFE88] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Histo__4817DA4F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactCDMVarSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactCDMVarSnapshot] (
    [RowID] int NOT NULL,
    [AssumptionID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [Amount_Comment] nvarchar(max) NOT NULL,
    [Amount_Formula] nvarchar(max) NOT NULL,
    [Comment] nvarchar(2000) NOT NULL,
    [TextValue] nvarchar(2000) NOT NULL,
    [TextValue_Comment] nvarchar(max) NOT NULL,
    [TextValue_Formula] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [FK_FactCDMVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Fisca__516315DF] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Fisca__52573A18] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__OBSna__534B5E51] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__543F828A] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__5533A6C3] DEFAULT ('') FOR [Amount_Comment]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__5627CAFC] DEFAULT ('d') FOR [Amount_Formula]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Comme__571BEF35] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__5810136E] DEFAULT ('') FOR [TextValue]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__590437A7] DEFAULT ('') FOR [TextValue_Comment]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__59F85BE0] DEFAULT ('d') FOR [TextValue_Formula]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__IsDel__5AEC8019] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Trans__5CD4C88B] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Histo__5BE0A452] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactDepartmentBudgetExceptions ------------------
---------------------------------------------
CREATE TABLE [ob].[FactDepartmentBudgetExceptions] (
    [RowID] int NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBExceptionsID] int NOT NULL,
    [Detail] nvarchar(2000) NOT NULL,
    [Acknowledged] bit NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [FK__FactDepar__Depar__761D0573] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [FK__FactDepar__OBExc__78054DE5] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Histo__7BD5DEC9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Depar__7528E13A] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__OBExc__771129AC] DEFAULT ((0)) FOR [OBExceptionsID]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Detai__78F9721E] DEFAULT ('') FOR [Detail]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Ackno__79ED9657] DEFAULT ((0)) FOR [Acknowledged]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__IsDel__7AE1BA90] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Trans__7CCA0302] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactDepartmentPrimaryStatisticConfigurationSubTableMap ------------------
---------------------------------------------
CREATE TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] (
    [RowID] int NOT NULL,
    [DepartmentalBudgetPHID] tinyint NOT NULL,
    [AccountPHID] int NOT NULL,
    [RowExpanded] int NOT NULL,
    [CellGUID] uniqueidentifier NOT NULL,
    [MeasureGUID] uniqueidentifier NOT NULL,
    [IsUserMapped] bit NOT NULL,
    [OBDepartmentalBudgetPHIndex] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [OBAccountPHIndex] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ([IsDeleted], [AccountPHID], [OBAccountPHIndex], [DepartmentalBudgetPHID], [OBDepartmentalBudgetPHIndex], [RowID]);
GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Histo__656E6F02] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__OBAcc__0E3B7A6B] DEFAULT ((0)) FOR [OBAccountPHIndex]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__CellG__5FB595AC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Measu__60A9B9E5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__RowEx__5EC17173] DEFAULT ((0)) FOR [RowExpanded]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__IsUse__619DDE1E] DEFAULT ((1)) FOR [IsUserMapped]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__OBDep__62920257] DEFAULT ((0)) FOR [OBDepartmentalBudgetPHIndex]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__IsDel__647A4AC9] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Trans__6662933B] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactGlobalStatisticExceptions ------------------
---------------------------------------------
CREATE TABLE [ob].[FactGlobalStatisticExceptions] (
    [RowID] int NOT NULL,
    [OBGlobalStatisticsPlanID] int NOT NULL,
    [OBExceptionsID] int NOT NULL,
    [Acknowledged] bit NOT NULL,
    [Detail] nvarchar(2000) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [FK__FactGloba__OBExc__0B1C1B0C] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [FK__FactGloba__OBGlo__0933D29A] FOREIGN KEY ([OBGlobalStatisticsPlanID]) REFERENCES [ob].[DimOBGlobalStatisticsPlan] ([OBGlobalStatisticsPlanID]); GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__OBGlo__083FAE61] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__OBExc__0A27F6D3] DEFAULT ((0)) FOR [OBExceptionsID]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Ackno__0C103F45] DEFAULT ((0)) FOR [Acknowledged]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Detai__0D04637E] DEFAULT ('') FOR [Detail]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__IsDel__0DF887B7] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Trans__0FE0D029] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Histo__0EECABF0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactGlobalStatisticsLink ------------------
---------------------------------------------
CREATE TABLE [ob].[FactGlobalStatisticsLink] (
    [RowID] int NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBGlobalStatisticsPlanID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [Version] timestamp NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_DepartmentalBudgetID] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_OBGlobalStatisticsPlanID] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactGlobalStatisticsSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactGlobalStatisticsSnapshot] (
    [RowID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OBGlobalStatisticID] int NOT NULL,
    [OBGlobalStatisticsPlanID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [Total] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactGlobalStatisticsSnapshot] ([OBSnapshotID], [OBGlobalStatisticsPlanID], [FiscalYearID], [TimeClassID], [OBGlobalStatisticID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactGlobalStatisticsSnapshot] ([OBSnapshotID], [OBGlobalStatisticsPlanID], [FiscalYearID], [TimeClassID], [OBGlobalStatisticID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__DataT__19BC12C2] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__Fisca__1BA45B34] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBGlo__1D8CA3A6] FOREIGN KEY ([OBGlobalStatisticID]) REFERENCES [ob].[DimOBGlobalStatistics] ([OBGlobalStatisticID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBGlo__1F74EC18] FOREIGN KEY ([OBGlobalStatisticsPlanID]) REFERENCES [ob].[DimOBGlobalStatisticsPlan] ([OBGlobalStatisticsPlanID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBSna__215D348A] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__TimeC__23457CFC] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__UnitT__252DC56E] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__DataT__18C7EE89] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Fisca__1AB036FB] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBGlo__1C987F6D] DEFAULT ((0)) FOR [OBGlobalStatisticID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBGlo__1E80C7DF] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBSna__20691051] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__TimeC__225158C3] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__UnitT__2439A135] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2621E9A7] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__27160DE0] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__280A3219] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Histo__36585170] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__28FE5652] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__29F27A8B] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2AE69EC4] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2BDAC2FD] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2CCEE736] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2DC30B6F] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2EB72FA8] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2FAB53E1] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__309F781A] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__31939C53] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Total__3287C08C] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Yearl__337BE4C5] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGlobalS__YTD__347008FE] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__IsDel__35642D37] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Trans__374C75A9] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactProviderSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactProviderSnapshot] (
    [RowID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactProviderSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [ProviderID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactProviderSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [ProviderID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__DataT__4EC4D7DE] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Depar__529568C2] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Fisca__50AD2050] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__OBFor__547DB134] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__OBSna__4CDC8F6C] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Provi__5665F9A6] FOREIGN KEY ([ProviderID]) REFERENCES [fw].[DimProvider] ([ProviderID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__TimeC__584E4218] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__UnitT__5A368A8A] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__OBSna__4BE86B33] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__DataT__4DD0B3A5] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__4FB8FC17] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Depar__51A14489] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__OBFor__53898CFB] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Provi__5571D56D] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__TimeC__575A1DDF] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__UnitT__59426651] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5B2AAEC3] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5C1ED2FC] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5D12F735] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5E071B6E] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5EFB3FA7] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5FEF63E0] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__60E38819] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__61D7AC52] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__62CBD08B] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__63BFF4C4] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__64B418FD] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__65A83D36] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Yearl__669C616F] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Histo__6B61168C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Total__679085A8] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvide__YTD__6884A9E1] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__6978CE1A] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__IsDel__6A6CF253] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Trans__6C553AC5] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactProviderVarSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactProviderVarSnapshot] (
    [RowID] int NOT NULL,
    [AssumptionID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [Amount_Comment] nvarchar(max) NOT NULL,
    [Amount_Formula] nvarchar(max) NOT NULL,
    [TextValue] nvarchar(2000) NOT NULL,
    [TextValue_Comment] nvarchar(max) NOT NULL,
    [TextValue_Formula] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [FK_FactProviderVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Histo__693A9F70] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__5FB13536] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__60A5596F] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__OBSna__61997DA8] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__628DA1E1] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__6381C61A] DEFAULT ('') FOR [Amount_Comment]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__6475EA53] DEFAULT ('d') FOR [Amount_Formula]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__656A0E8C] DEFAULT ('') FOR [TextValue]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__665E32C5] DEFAULT ('') FOR [TextValue_Comment]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__675256FE] DEFAULT ('d') FOR [TextValue_Formula]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__IsDel__68467B37] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Trans__6A2EC3A9] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReimbursementAccountSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReimbursementAccountSnapshot] (
    [RowID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OBReimbursementPlanID] int NOT NULL,
    [PatientReimbursementGroupID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReimbursementAccountSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [AccountID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReimbursementAccountSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [AccountID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Accou__720E141B] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__DataT__73F65C8D] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Fisca__75DEA4FF] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__OBRei__77C6ED71] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__OBSna__7025CBA9] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Patie__79AF35E3] FOREIGN KEY ([PatientReimbursementGroupID]) REFERENCES [fw].[DimPatientReimbursementGroup] ([PatientReimbursementGroupID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__TimeC__7B977E55] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__UnitT__7D7FC6C7] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__005C3372] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__015057AB] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__02447BE4] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0338A01D] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__042CC456] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0520E88F] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__06150CC8] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__07093101] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__07FD553A] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__08F17973] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimbur__YTD__09E59DAC] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Yearl__0AD9C1E5] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Total__0BCDE61E] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0CC20A57] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Histo__0EAA52C9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__IsDel__0DB62E90] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Trans__0F9E7702] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__OBSna__6F31A770] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Accou__7119EFE2] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__DataT__73023854] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Fisca__74EA80C6] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__OBRei__76D2C938] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Patie__78BB11AA] DEFAULT ((0)) FOR [PatientReimbursementGroupID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__TimeC__7AA35A1C] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__UnitT__7C8BA28E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__7E73EB00] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__7F680F39] DEFAULT ((0)) FOR [Month02]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReimbursementExceptions ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReimbursementExceptions] (
    [RowID] int NOT NULL,
    [OBReimbursementPlanID] int NOT NULL,
    [OBExceptionsID] int NOT NULL,
    [Acknowledged] bit NOT NULL,
    [Detail] nvarchar(2000) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [FK__FactReimb__OBExc__1599A97F] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [FK__FactReimb__OBRei__13B1610D] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__OBRei__12BD3CD4] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__OBExc__14A58546] DEFAULT ((0)) FOR [OBExceptionsID]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Ackno__168DCDB8] DEFAULT ((0)) FOR [Acknowledged]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Detai__1781F1F1] DEFAULT ('') FOR [Detail]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__IsDel__1876162A] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Trans__1A5E5E9C] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Histo__196A3A63] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReimbursementPayorSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReimbursementPayorSnapshot] (
    [RowID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [OBReimbursementPlanID] int NOT NULL,
    [PatientReimbursementGroupID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [YTD] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReimbursementPayorSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [OBForecastDetailID], [PayorGroupID], [PayorID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReimbursementPayorSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [OBForecastDetailID], [PayorGroupID], [PayorID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__DataT__249993E8] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Fisca__15575058] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBFor__173F98CA] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBRei__1927E13C] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBSna__136F07E6] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Patie__1B1029AE] FOREIGN KEY ([PatientReimbursementGroupID]) REFERENCES [fw].[DimPatientReimbursementGroup] ([PatientReimbursementGroupID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Payor__1CF87220] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Payor__1EE0BA92] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__TimeC__20C90304] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__UnitT__22B14B76] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBSna__127AE3AD] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Fisca__14632C1F] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBFor__164B7491] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Histo__35C41FEA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBRei__1833BD03] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Patie__1A1C0575] DEFAULT ((0)) FOR [PatientReimbursementGroupID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Payor__1C044DE7] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Payor__1DEC9659] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__TimeC__1FD4DECB] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__UnitT__21BD273D] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__DataT__23A56FAF] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__258DB821] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2681DC5A] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__27760093] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__286A24CC] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__295E4905] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2A526D3E] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2B469177] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2C3AB5B0] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2D2ED9E9] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2E22FE22] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2F17225B] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__300B4694] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__30FF6ACD] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimbur__YTD__31F38F06] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Yearl__32E7B33F] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Total__33DBD778] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__IsDel__34CFFBB1] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Trans__36B84423] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReportAccountWithStaffingDetail ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReportAccountWithStaffingDetail] (
    [RowID] bigint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [AccountID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactReportAccountWithStaffingDetail_Clustered] ON [ob].[FactReportAccountWithStaffingDetail] ([DepartmentalBudgetID]);
GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__229C6EA7] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__239092E0] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactReportA__YTD__2484B719] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Total__2578DB52] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Modif__266CFF8B] DEFAULT (getdate()) FOR [ModifiedAt]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Depar__126606DE] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Accou__135A2B17] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__JobCo__144E4F50] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__PayCo__15427389] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Fisca__163697C2] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__TimeC__172ABBFB] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__UnitT__181EE034] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1913046D] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1A0728A6] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1AFB4CDF] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1BEF7118] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1CE39551] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1DD7B98A] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1ECBDDC3] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1FC001FC] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__20B42635] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__21A84A6E] DEFAULT ((0)) FOR [Month10]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReportFinancialStatement ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReportFinancialStatement] (
    [RowID] bigint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [SnapshotID] int NOT NULL,
    [ModifiedAt] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactReportFinancialStatement_Clustered] ON [ob].[FactReportFinancialStatement] ([FiscalYearID]);
CREATE NONCLUSTERED INDEX [IDX_FactReportFinancialStatement_AllKeys] ON [ob].[FactReportFinancialStatement] ([DepartmentalBudgetID], [SnapshotID], [TimeClassID], [FiscalYearID], [FinancialReportingID], [AccountID]);
GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [FK_FactReportFinancialStatement_SnapshotID] FOREIGN KEY ([SnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Depar__3EE3A79A] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Depar__3FD7CBD3] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Accou__40CBF00C] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Finan__41C01445] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Fisca__42B4387E] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__TimeC__43A85CB7] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__449C80F0] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4590A529] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4684C962] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4778ED9B] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__486D11D4] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4961360D] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4A555A46] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4B497E7F] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4C3DA2B8] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4D31C6F1] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4E25EB2A] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4F1A0F63] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactReportF__YTD__500E339C] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Yearl__510257D5] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Total__51F67C0E] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Snaps__52EAA047] DEFAULT ((0)) FOR [SnapshotID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Modif__53DEC480] DEFAULT (getdate()) FOR [ModifiedAt]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReportFinancialStatement_Pivoted ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReportFinancialStatement_Pivoted] (
    [RowID] bigint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [SnapshotID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [MaxValue] decimal NOT NULL,
    [MaxValueYTD] decimal NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactReportFinancialStatement_Pivoted_Clustered] ON [ob].[FactReportFinancialStatement_Pivoted] ([FiscalYearID]);
CREATE NONCLUSTERED INDEX [IDX_FactReportFinancialStatement_Pivoted_AllKeys] ON [ob].[FactReportFinancialStatement_Pivoted] ([DepartmentalBudgetID], [SnapshotID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [FinancialReportingID], [AccountID]);
GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [FK_FactReportFinancialStatement_Pivoted_SnapshotID] FOREIGN KEY ([SnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__TimeC__41AC9C5A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Fisca__42A0C093] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Depar__4394E4CC] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Finan__44890905] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Accou__457D2D3E] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Snaps__46715177] DEFAULT ((0)) FOR [SnapshotID]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Amoun__476575B0] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Total__485999E9] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Yearl__494DBE22] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactReportF__YTD__4A41E25B] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__MaxVa__4B360694] DEFAULT ((0)) FOR [MaxValue]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__MaxVa__4C2A2ACD] DEFAULT ((0)) FOR [MaxValueYTD]; GO
ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Fisca__4D1E4F06] DEFAULT ((0)) FOR [FiscalMonthID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactReportingMonthlySnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactReportingMonthlySnapshot] (
    [RowID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReportingMonthlySnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [FinancialReportingID], [IsDeleted]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReportingMonthlySnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [FinancialReportingID], [IsDeleted]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentalBudget_OBSnapshotID] ON [ob].[FactReportingMonthlySnapshot] ([DepartmentalBudgetID], [OBSnapshotID]);
GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Depar__3E5965EB] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Finan__4041AE5D] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Fisca__3C711D79] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__OBSna__3A88D507] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__TimeC__4229F6CF] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__OBSna__3994B0CE] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Fisca__3B7CF940] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Depar__3D6541B2] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Finan__3F4D8A24] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__TimeC__4135D296] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__431E1B08] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__44123F41] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4506637A] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__45FA87B3] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__46EEABEC] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__47E2D025] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__48D6F45E] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__49CB1897] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4ABF3CD0] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4BB36109] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4CA78542] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4D9BA97B] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactReporti__YTD__4E8FCDB4] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Yearl__4F83F1ED] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Total__50781626] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__IsDel__516C3A5F] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Trans__535482D1] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Histo__52605E98] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactServiceLineExceptions ------------------
---------------------------------------------
CREATE TABLE [ob].[FactServiceLineExceptions] (
    [RowID] int NOT NULL,
    [OBServiceLinePlanID] int NOT NULL,
    [OBExceptionsID] int NOT NULL,
    [Acknowledged] bit NOT NULL,
    [Detail] nvarchar(2000) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [FK__FactServi__OBExc__201737F2] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [FK__FactServi__OBSer__1E2EEF80] FOREIGN KEY ([OBServiceLinePlanID]) REFERENCES [ob].[DimOBServiceLinePlan] ([OBServiceLinePlanID]); GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Histo__23E7C8D6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__OBSer__1D3ACB47] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__OBExc__1F2313B9] DEFAULT ((0)) FOR [OBExceptionsID]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Ackno__210B5C2B] DEFAULT ((0)) FOR [Acknowledged]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Detai__21FF8064] DEFAULT ('') FOR [Detail]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__IsDel__22F3A49D] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Trans__24DBED0F] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactServiceLineSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactServiceLineSnapshot] (
    [RowID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [ModelingServiceLineID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [OBServiceLinePlanID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [Total] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactServiceLineSnapshot] ([OBSnapshotID], [OBServiceLinePlanID], [FiscalYearID], [TimeClassID], [ModelingServiceLineID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactServiceLineSnapshot] ([OBSnapshotID], [OBServiceLinePlanID], [FiscalYearID], [TimeClassID], [ModelingServiceLineID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__DataT__572513B5] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__Fisca__590D5C27] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__Model__5AF5A499] FOREIGN KEY ([ModelingServiceLineID]) REFERENCES [fw].[DimModelingServiceLine] ([ModelingServiceLineID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBFor__5CDDED0B] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBSer__60AE7DEF] FOREIGN KEY ([OBServiceLinePlanID]) REFERENCES [ob].[DimOBServiceLinePlan] ([OBServiceLinePlanID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBSna__5EC6357D] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__TimeC__6296C661] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__UnitT__647F0ED3] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Histo__74B5769C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__DataT__5630EF7C] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Fisca__581937EE] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Model__5A018060] DEFAULT ((0)) FOR [ModelingServiceLineID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBFor__5BE9C8D2] DEFAULT ((0)) FOR [OBForecastDetailID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBSna__5DD21144] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBSer__5FBA59B6] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__TimeC__61A2A228] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__UnitT__638AEA9A] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6573330C] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__66675745] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__675B7B7E] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__684F9FB7] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6943C3F0] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6A37E829] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6B2C0C62] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6C20309B] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6D1454D4] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6E08790D] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6EFC9D46] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6FF0C17F] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Yearl__70E4E5B8] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactService__YTD__71D909F1] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Total__72CD2E2A] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__IsDel__73C15263] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Trans__75A99AD5] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactStaffingPCSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactStaffingPCSnapshot] (
    [RowID] int NOT NULL,
    [DataTypeID] tinyint NOT NULL,
    [EmployeeID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [JobCodeID] int NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [PayCodeID] smallint NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Month01] decimal NOT NULL,
    [Month02] decimal NOT NULL,
    [Month03] decimal NOT NULL,
    [Month04] decimal NOT NULL,
    [Month05] decimal NOT NULL,
    [Month06] decimal NOT NULL,
    [Month07] decimal NOT NULL,
    [Month08] decimal NOT NULL,
    [Month09] decimal NOT NULL,
    [Month10] decimal NOT NULL,
    [Month11] decimal NOT NULL,
    [Month12] decimal NOT NULL,
    [MonthsLoaded] int NOT NULL,
    [Total] decimal NOT NULL,
    [Yearly] decimal NOT NULL,
    [YTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactStaffingPCSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [TimeClassID], [FiscalYearID], [JobCodeID], [EmployeeID], [PayCodeGroupID], [PayCodeID], [UnitTypeID], [IsDeleted], [DataTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactStaffingPCSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [TimeClassID], [FiscalYearID], [JobCodeID], [EmployeeID], [PayCodeGroupID], [PayCodeID], [UnitTypeID], [IsDeleted], [DataTypeID]);
GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__DataT__3B1D068D] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Depar__42BE2855] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Emplo__3D054EFF] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Fisca__3EED9771] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__JobCo__40D5DFE3] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__OBSna__44A670C7] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__PayCo__468EB939] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__TimeC__487701AB] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__UnitT__4A5F4A1D] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__DataT__3A28E254] DEFAULT ((0)) FOR [DataTypeID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Emplo__3C112AC6] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__3DF97338] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__JobCo__3FE1BBAA] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Depar__41CA041C] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__OBSna__43B24C8E] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__PayCo__459A9500] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__TimeC__4782DD72] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__UnitT__496B25E4] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4B536E56] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4C47928F] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4D3BB6C8] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4E2FDB01] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4F23FF3A] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__50182373] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__510C47AC] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__52006BE5] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__52F4901E] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__53E8B457] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__54DCD890] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__55D0FCC9] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__56C52102] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Total__57B9453B] DEFAULT ((0)) FOR [Total]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Yearl__58AD6974] DEFAULT ((0)) FOR [Yearly]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaffin__YTD__59A18DAD] DEFAULT ((0)) FOR [YTD]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__IsDel__5A95B1E6] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Trans__5C7DFA58] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Histo__5B89D61F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactStaffingPCVarSnapshot ------------------
---------------------------------------------
CREATE TABLE [ob].[FactStaffingPCVarSnapshot] (
    [RowID] bigint NOT NULL,
    [AssumptionID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [JobCodeID] int NOT NULL,
    [DepartmentalBudgetID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [OBSnapshotID] int NOT NULL,
    [Amount] decimal NOT NULL,
    [Amount_Comment] nvarchar(max) NOT NULL,
    [Amount_Formula] nvarchar(max) NOT NULL,
    [Comment] nvarchar(2000) NOT NULL,
    [Comment_Comment] nvarchar(max) NOT NULL,
    [Comment_Formula] nvarchar(max) NOT NULL,
    [TextValue] nvarchar(2000) NOT NULL,
    [TextValue_Comment] nvarchar(max) NOT NULL,
    [TextValue_Formula] nvarchar(max) NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [FK_FactStaffingPCVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Histo__79710739] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__6D0B3054] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__6DFF548D] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__OBSna__6EF378C6] DEFAULT ((0)) FOR [OBSnapshotID]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__6FE79CFF] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__70DBC138] DEFAULT ('') FOR [Amount_Comment]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__71CFE571] DEFAULT ('d') FOR [Amount_Formula]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__72C409AA] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__73B82DE3] DEFAULT ('') FOR [Comment_Comment]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__74AC521C] DEFAULT ('d') FOR [Comment_Formula]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__75A07655] DEFAULT ('') FOR [TextValue]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__76949A8E] DEFAULT ('') FOR [TextValue_Comment]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__7788BEC7] DEFAULT ('d') FOR [TextValue_Formula]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__IsDel__787CE300] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Trans__7A652B72] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FactStagedDSChargeCodeCost ------------------
---------------------------------------------
CREATE TABLE [ob].[FactStagedDSChargeCodeCost] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [FinancialCostComponentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [Units] decimal NOT NULL,
    [Cost] decimal NOT NULL,
    [Charge] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Servi__0EDF5CF3] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__AgeCo__0FD3812C] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Patie__10C7A565] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Medic__11BBC99E] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Depar__6276CAD0] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Fisca__645F1342] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Fisca__6553377B] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__TimeC__66475BB4] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Finan__673B7FED] DEFAULT ((0)) FOR [FinancialCostComponentID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Charg__682FA426] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Units__6923C85F] DEFAULT ((0)) FOR [Units]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStaged__Cost__6A17EC98] DEFAULT ((0)) FOR [Cost]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Charg__6B0C10D1] DEFAULT ((0)) FOR [Charge]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__IsDel__6C00350A] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Histo__6CF45943] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Trans__6DE87D7C] DEFAULT ((0)) FOR [TransactionID]; GO

---------------------------------------------

---------------------------------------------
-- ob.FlexDriver ------------------
---------------------------------------------
CREATE TABLE [ob].[FlexDriver] (
    [FlexDriverGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [ScoreDatatableGUID] uniqueidentifier NOT NULL,
    [ParentDriverGUID] uniqueidentifier NOT NULL,
    [IsParentDriverFlexed] bit NOT NULL,
    [SortOrder] smallint NOT NULL,
    [Tier] smallint NOT NULL,
    [MeasureType] tinyint NOT NULL,
    [IsSameJobCode] bit NOT NULL,
    [IsSamePayCodeGroup] bit NOT NULL,
    PRIMARY KEY ([FlexDriverGUID])
);
GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Paren__34A51328] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentDriverGUID]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsPar__35993761] DEFAULT ((0)) FOR [IsParentDriverFlexed]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__SortO__368D5B9A] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDriver__Tier__37817FD3] DEFAULT ((0)) FOR [Tier]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsSam__3FCCAD11] DEFAULT ((0)) FOR [IsSameJobCode]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsSam__40C0D14A] DEFAULT ((0)) FOR [IsSamePayCodeGroup]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__FlexD__598BB3BD] DEFAULT (newid()) FOR [FlexDriverGUID]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDriver__Name__5A7FD7F6] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Score__5B73FC2F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreDatatableGUID]; GO
ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Measu__632AF7E7] DEFAULT ((0)) FOR [MeasureType]; GO

---------------------------------------------

---------------------------------------------
-- ob.FlexDriverAccountAssignment ------------------
---------------------------------------------
CREATE TABLE [ob].[FlexDriverAccountAssignment] (
    [FlexDriverAccountAssignmentID] int NOT NULL,
    [FlexDriverGUID] uniqueidentifier NOT NULL,
    [AccountAssignment] nvarchar(400) NOT NULL,
    PRIMARY KEY ([FlexDriverAccountAssignmentID])
);
GO
ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__28B43D8F] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO
ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__5E5068DA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO
ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [DF__FlexDrive__Accou__6038B14C] DEFAULT ('') FOR [AccountAssignment]; GO

---------------------------------------------

---------------------------------------------
-- ob.FlexDriverPayrollAssignment ------------------
---------------------------------------------
CREATE TABLE [ob].[FlexDriverPayrollAssignment] (
    [FlexDriverPayrollAssignmentID] int NOT NULL,
    [FlexDriverGUID] uniqueidentifier NOT NULL,
    [JobCodeAssignment] nvarchar(400) NOT NULL,
    [PayCodeGroupAssignment] nvarchar(400) NOT NULL,
    PRIMARY KEY ([FlexDriverPayrollAssignmentID])
);
GO
ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__29A861C8] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO
ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__63151DF7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO
ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__JobCo__64FD6669] DEFAULT ('') FOR [JobCodeAssignment]; GO
ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__PayCo__65F18AA2] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO

---------------------------------------------

---------------------------------------------
-- ob.FlexDriverProviderForecastAssignment ------------------
---------------------------------------------
CREATE TABLE [ob].[FlexDriverProviderForecastAssignment] (
    [FlexDriverProviderForecastAssignmentID] int NOT NULL,
    [FlexDriverGUID] uniqueidentifier NOT NULL,
    [ProviderAssignment] nvarchar(400) NULL,
    [ForecastDetailAssignment] nvarchar(400) NULL,
    PRIMARY KEY ([FlexDriverProviderForecastAssignmentID])
);
GO
ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__23B61DD2] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO
ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__20D9B127] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO
ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__Provi__21CDD560] DEFAULT ('') FOR [ProviderAssignment]; GO
ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__Forec__22C1F999] DEFAULT ('') FOR [ForecastDetailAssignment]; GO

---------------------------------------------

---------------------------------------------
-- ob.JobCodeReconciliationTarget ------------------
---------------------------------------------
CREATE TABLE [ob].[JobCodeReconciliationTarget] (
    [TargetGuid] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [JobCodeID] int NOT NULL,
    [Amount] decimal NOT NULL,
    PRIMARY KEY ([TargetGuid])
);
GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Entit__1D428AE3] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Fisca__1F2AD355] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Fisca__21131BC7] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__JobCo__26CBF51D] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__TimeC__22FB6439] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__UnitT__24E3ACAB] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Targe__1B5A4271] DEFAULT (newid()) FOR [TargetGuid]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Fisca__1E36AF1C] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Fisca__201EF78E] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__TimeC__22074000] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__UnitT__23EF8872] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__JobCo__25D7D0E4] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Amoun__27C01956] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Entit__1C4E66AA] DEFAULT ((0)) FOR [EntityID]; GO

---------------------------------------------

---------------------------------------------
-- ob.PayCodeReconciliationTarget ------------------
---------------------------------------------
CREATE TABLE [ob].[PayCodeReconciliationTarget] (
    [TargetGuid] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [Amount] decimal NOT NULL,
    PRIMARY KEY ([TargetGuid])
);
GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Entit__183DDEA4] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Fisca__1A262716] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Fisca__1C0E6F88] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__PayCo__21C748DE] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__TimeC__1DF6B7FA] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__UnitT__1FDF006C] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Targe__16559632] DEFAULT (newid()) FOR [TargetGuid]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Fisca__193202DD] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Fisca__1B1A4B4F] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__TimeC__1D0293C1] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__UnitT__1EEADC33] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__PayCo__20D324A5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Amoun__22BB6D17] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Entit__1749BA6B] DEFAULT ((0)) FOR [EntityID]; GO

---------------------------------------------

---------------------------------------------
-- ob.PayrollVariabilityOverride ------------------
---------------------------------------------
CREATE TABLE [ob].[PayrollVariabilityOverride] (
    [DepartmentAssignment] nvarchar(400) NOT NULL,
    [JobCodeAssignment] nvarchar(400) NOT NULL,
    [PayCodeGroupAssignment] nvarchar(400) NOT NULL,
    [Variability] decimal NOT NULL,
    [PrecedentOrder] int NOT NULL,
    [PayrollVariabilityOverrideID] int NOT NULL,
    PRIMARY KEY ([PayrollVariabilityOverrideID])
);
GO
ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Depar__6F7AF4DC] DEFAULT ('') FOR [DepartmentAssignment]; GO
ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__JobCo__706F1915] DEFAULT ('') FOR [JobCodeAssignment]; GO
ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__PayCo__71633D4E] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO
ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Varia__72576187] DEFAULT ((0)) FOR [Variability]; GO
ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Prece__734B85C0] DEFAULT ((0)) FOR [PrecedentOrder]; GO

---------------------------------------------

---------------------------------------------
-- ob.PayrollVariabilityOverrideCache ------------------
---------------------------------------------
CREATE TABLE [ob].[PayrollVariabilityOverrideCache] (
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [Variability] decimal NOT NULL,
    [IsForAllPayCodeGroups] bit NOT NULL,
    PRIMARY KEY ([DepartmentID], [JobCodeID], [PayCodeGroupID])
);
GO
ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimJobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimPayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [DF__PayrollVa__IsFor__0E911584] DEFAULT ((0)) FOR [IsForAllPayCodeGroups]; GO

---------------------------------------------

---------------------------------------------
-- ob.ReconciliationTarget ------------------
---------------------------------------------
CREATE TABLE [ob].[ReconciliationTarget] (
    [TargetGuid] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Amount] decimal NOT NULL,
    PRIMARY KEY ([TargetGuid])
);
GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Entit__22E3F39B] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Finan__289CCCF1] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Fisca__24CC3C0D] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Fisca__26B4847F] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__TimeC__2A851563] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Targe__20FBAB29] DEFAULT (newid()) FOR [TargetGuid]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Fisca__23D817D4] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Fisca__25C06046] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Finan__27A8A8B8] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__TimeC__2990F12A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Amoun__2B79399C] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Entit__21EFCF62] DEFAULT ((0)) FOR [EntityID]; GO

---------------------------------------------

---------------------------------------------
-- ob.StatisticsEntityReconciliationTarget ------------------
---------------------------------------------
CREATE TABLE [ob].[StatisticsEntityReconciliationTarget] (
    [TargetGuid] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AccountID] int NOT NULL,
    [Amount] decimal NOT NULL,
    PRIMARY KEY ([TargetGuid])
);
GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Accou__50C22EE9] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Entit__4738C4AF] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Fisca__49210D21] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Fisca__4B095593] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__TimeC__4CF19E05] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__UnitT__4ED9E677] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Targe__45507C3D] DEFAULT (newid()) FOR [TargetGuid]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Fisca__482CE8E8] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Fisca__4A15315A] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__TimeC__4BFD79CC] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__UnitT__4DE5C23E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Accou__4FCE0AB0] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Amoun__51B65322] DEFAULT ((0)) FOR [Amount]; GO
ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Entit__4644A076] DEFAULT ((0)) FOR [EntityID]; GO

---------------------------------------------

---------------------------------------------
-- ob.SystemSetting ------------------
---------------------------------------------
CREATE TABLE [ob].[SystemSetting] (
    [SystemSettingID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Description] nvarchar(400) NOT NULL,
    [Value] nvarchar(max) NOT NULL,
    [IsEditable] bit NOT NULL,
    [ColumnType] int NOT NULL,
    [DefaultValue] nvarchar(100) NOT NULL,
    [IsEncrypted] bit NOT NULL,
    PRIMARY KEY ([SystemSettingID])
);
GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__5E065017] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__5EFA7450] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__60E2BCC2] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__61D6E0FB] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__62CB0534] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__6AA45E82] DEFAULT ((0)) FOR [IsEncrypted]; GO

---------------------------------------------
---------------------------------------------
--  VIEWS
---------------------------------------------

-- ob.viewAllocationBasis
/************************************************************
** Author: Joel Gerber
** Create Date: 7/29/2014
** Description: Displays the basis values for each allocation and department
** Last Modified: 2014-07-29
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**  1		2014-09-05	JG				Changing the way basis is linked to allocations
**  2		2014-09-11	JG				Filter out deleted rows
**  3		2014-09-22	JG				Adding Department Mapping Basis Views
**  4		2015-01-28	MS				Adding support for YTD-driven basis
**	5		2015-08-06	CB		D-02673	Added unittypeid to factaccount joins
*************************************************************/
CREATE view [ob].[viewAllocationBasis]
AS

/** Account Basis for Account Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2 
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			db.DepartmentalBudgetID,
			al.OBAllocationBasisID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** Account Basis for Department Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join  (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2 
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			db.DepartmentalBudgetID,
			al.OBAllocationBasisID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join  (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** Financial Reporting Basis for Account Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(Total) as Total 
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
			
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** Financial Reporting Basis for Department Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(Total) as Total 
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
		
	group by 
			al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(Total) as Total
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID<>100 --YTD
			and TimeClassID=2
			and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
			and Total<>0
			and ab.IsDeleted=0
			
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** Custom Basis ***************************************************/
select 	
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
from 	
	(select
		al.OBAllocationID,
		al.OBAllocationBasisID,
		db.DepartmentalBudgetID,
		db.DepartmentID,
		sum(BasisValue) as Total
	from	
		[clientob].[FactAllocationCustomBasis] cb
		inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=cb.OBAllocationBasisID
		inner join [ob].[DimDepartmentalBudget] db on cb.DepartmentTargetID=db.DepartmentID
	where
		cb.isdeleted=0
	group by 
		al.OBAllocationID,
		al.OBAllocationBasisID,
		db.DepartmentalBudgetID,
		db.DepartmentID) as DepartmentLevel
inner join
	(select
		al.OBAllocationID,
		sum(BasisValue) as Total
	from	
		[clientob].[FactAllocationCustomBasis] cb
		inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=cb.OBAllocationBasisID
		inner join [ob].[DimDepartmentalBudget] db on cb.DepartmentTargetID=db.DepartmentID
	where 
		BasisValue>0 and cb.isdeleted=0
	group by 
		al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** YTD Account Basis for Account Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			db.DepartmentalBudgetID,
			al.OBAllocationBasisID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** YTD Account Basis for Department Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			db.DepartmentalBudgetID,
			al.OBAllocationBasisID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactAccount] fa 
				on db.DepartmentalBudgetID=fa.DepartmentalBudgetID 
				and ab.AccountID=fa.AccountID
				and ab.UnitTypeID=fa.UnitTypeID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD 
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** YTD Financial Reporting Basis for Account Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(YTD) as Total 
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD 
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
	group by 
			al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD 
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
			
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID

UNION ALL

/** YTD Financial Reporting Basis for Department Mapping***************************************************/
select
	DepartmentLevel.OBAllocationID,
	DepartmentLevel.OBAllocationBasisID,
	DepartmentLevel.DepartmentalBudgetID,
	DepartmentLevel.DepartmentID,
	DepartmentLevel.Total as BasisValue,
	ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage
	
from
	(select al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID,
			SUM(YTD) as Total 
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD 
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
		
	group by 
			al.OBAllocationID,
			al.OBAllocationBasisID,
			db.DepartmentalBudgetID,
			db.DepartmentID) as DepartmentLevel
inner join
	(select al.OBAllocationID,
			SUM(YTD) as Total
	from 	[clientob].[FactAllocationFinancialReportingBasis] ab
			inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID
			inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID
			inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID
			inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID
			inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID
	where 
			dab.OBForecastDetailID=100 --YTD 
			and TimeClassID=1
			and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year')
			and YTD<>0
			and ab.IsDeleted=0
			
	group by 
			al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID
GO


---------------------------------------------

-- ob.viewAllocationValues
create view [ob].[viewAllocationValues]
as
/*****************************************************************************************
** Author: Joel Gerber
** Create Date: 7/29/2014
** Description: Displays the source and target departments and accounts and their allocation values
** Last Modified: 2014-07-29
** GM Release: 2014.4
*****************************************************************************************
** Change History
*****************************************************************************************
** CID	Date		Author	WI		Description
** 1	2014-09-04	JG				Add the department filter
** 2	2014-09-11 	JG				Add the reversal
** 3	2014-09-22	JG				Add ability to use a default (not specified) account for the department mapping
** 4	2014-09-24	JG				Only reverse if reverse is being used
** 5	2014-09-25	JG				Changing allocation to pull the allocation percentage
** 6	2014-09-26	JG				Adding isReverse flag for reporting purposes
** 7 	2014-09-30	JG				Allowing non-dollars to be allocated
** 8	2015-02-17	JG				Adding an isDeleted Filter to the filter table
** 9	2015-09-02	cbb		D-03357 Backing out CID 7 because the model does not support non-dollar unittypes
** 10	2016-02-10	cbb		B-11086	Adding execution order
*****************************************************************************************/
--Account Mapping (Reverse)
select 
	aa.OBAllocationID,
	dm.ExecutionOrder, -- CID 10
	fa.DepartmentalBudgetID as DepartmentalBudgetSourceID,
	aa.DepartmentSourceID,
	aa.AccountSourceID, 
	db2.DepartmentalBudgetID as DepartmentalBudgetTargetID,
	aa.DepartmentID as DepartmentTargetID,
	aa.AccountID as AccountTargetID,
	fa.FiscalYearID, 
	fa.TimeClassId, 
	fa.UnitTypeID, 
	fa.DataTypeID,
	1 as isReverse,
	-aa.AllocationPercentage as AllocationPercentage,
	-fa.Month01*aa.AllocationPercentage as Month01, 
	-fa.Month02*aa.AllocationPercentage as Month02,
	-fa.Month03*aa.AllocationPercentage as Month03,
	-fa.Month04*aa.AllocationPercentage as Month04,
	-fa.Month05*aa.AllocationPercentage as Month05,
	-fa.Month06*aa.AllocationPercentage as Month06,
	-fa.Month07*aa.AllocationPercentage as Month07,
	-fa.Month08*aa.AllocationPercentage as Month08,
	-fa.Month09*aa.AllocationPercentage as Month09,
	-fa.Month10*aa.AllocationPercentage as Month10,
	-fa.Month11*aa.AllocationPercentage as Month11,
	-fa.Month12*aa.AllocationPercentage as Month12,
	-fa.Total*aa.AllocationPercentage as Total
from 
	[clientob].[FactAccount] fa
	inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [clientob].[FactAllocationAccountMapping] aa on db.DepartmentID=aa.DepartmentSourceID and fa.AccountID=aa.AccountSourceID
	inner join [ob].[DimOBAllocation] dm on aa.OBAllocationID=dm.OBAllocationID -- CID 10
	inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=aa.DepartmentID
where 
	TimeClassID=2
	and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
	/*** CID9 Start****************************************************************/
	and fa.UnitTypeID=34
	/*** CID9 END******************************************************************/
	and fa.Total<>0
	and aa.IsDeleted=0
	/*** CI4 Start - If reverse department is not specified, don't do anything ***/
	and aa.DepartmentID<>0
	/*** CI4 END******************************************************************/

UNION ALL

--Account Mapping (Direct)
select 
	aa.OBAllocationID,
	dm.ExecutionOrder, -- CID 10
	fa.DepartmentalBudgetID as DepartmentalBudgetSourceID,
	aa.DepartmentSourceID,
	aa.AccountSourceID, 
	db2.DepartmentalBudgetID as DepartmentalBudgetTargetID,
	aa.DepartmentTargetID,
	aa.AccountTargetID,
	fa.FiscalYearID, 
	fa.TimeClassId, 
	fa.UnitTypeID, 
	fa.DataTypeID,
	0 as isReverse,
	aa.AllocationPercentage,
	fa.Month01*aa.AllocationPercentage as Month01, 
	fa.Month02*aa.AllocationPercentage as Month02,
	fa.Month03*aa.AllocationPercentage as Month03,
	fa.Month04*aa.AllocationPercentage as Month04,
	fa.Month05*aa.AllocationPercentage as Month05,
	fa.Month06*aa.AllocationPercentage as Month06,
	fa.Month07*aa.AllocationPercentage as Month07,
	fa.Month08*aa.AllocationPercentage as Month08,
	fa.Month09*aa.AllocationPercentage as Month09,
	fa.Month10*aa.AllocationPercentage as Month10,
	fa.Month11*aa.AllocationPercentage as Month11,
	fa.Month12*aa.AllocationPercentage as Month12,
	fa.Total*aa.AllocationPercentage as Total
from 
	[clientob].[FactAccount] fa
	inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [clientob].[FactAllocationAccountMapping] aa on db.DepartmentID=aa.DepartmentSourceID and fa.AccountID=aa.AccountSourceID
	inner join [ob].[DimOBAllocation] dm on aa.OBAllocationID=dm.OBAllocationID -- CID 10
	inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=aa.DepartmentTargetID	
where 
	TimeClassID=2
	and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
	/*** CID9 Start****************************************************************/
	and fa.UnitTypeID=34
	/*** CID9 END******************************************************************/
	and fa.Total<>0
	and aa.IsDeleted=0

UNION ALL

--Department Mapping (Reverse)
select 
	da.OBAllocationID,
	dm.ExecutionOrder, -- CID 10
	fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, 
	da.DepartmentSourceID,
	fa.AccountID as AccountSourceID, 
	db2.DepartmentalBudgetID as DepartmentalBudgetTargetID,
	da.DepartmentID as DepartmentTargetID,
	/*** START CID 3 ***********************************************/
	ra.AccountID as AccountTargetID,
	/*** END CID 3 *************************************************/
	fa.FiscalYearID, 
	fa.TimeClassId, 
	fa.UnitTypeID, 
	fa.DataTypeID,
	1 as isReverse,
	-da.AllocationPercentage as AllocationPercentage,
	-fa.Month01*da.AllocationPercentage as Month01, 
	-fa.Month02*da.AllocationPercentage as Month02,
	-fa.Month03*da.AllocationPercentage as Month03,
	-fa.Month04*da.AllocationPercentage as Month04,
	-fa.Month05*da.AllocationPercentage as Month05,
	-fa.Month06*da.AllocationPercentage as Month06,
	-fa.Month07*da.AllocationPercentage as Month07,
	-fa.Month08*da.AllocationPercentage as Month08,
	-fa.Month09*da.AllocationPercentage as Month09,
	-fa.Month10*da.AllocationPercentage as Month10,
	-fa.Month11*da.AllocationPercentage as Month11,
	-fa.Month12*da.AllocationPercentage as Month12,
	-fa.Total*da.AllocationPercentage as Total
from 
	[clientob].[FactAccount] fa
	inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [clientob].[FactAllocationDepartmentMapping] da on db.DepartmentID=da.DepartmentSourceID 
	inner join [ob].[DimOBAllocation] dm on da.OBAllocationID=dm.OBAllocationID -- CID 10
	inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=da.DepartmentID
	inner join [fw].[DimAccount] acc on fa.AccountID=acc.AccountID
	/*** START CID 3 ***********************************************/
	inner join [fw].[DimAccount] ra on ra.AccountID= case when da.AccountID=0 then fa.AccountID else da.AccountID end
	/*** END CID 3 *************************************************/
	inner join [clientob].[FactAllocationDepartmentMappingFilter] daf on daf.OBAllocationID=da.OBAllocationID and daf.FinancialReportingID=acc.OBDollarsFinancialReportingID
where 
	fa.TimeClassID=2
	and fa.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
	and fa.Total<>0
	/*** CID9 Start****************************************************************/
	and fa.UnitTypeID=34
	/*** CID9 END******************************************************************/
	and da.IsDeleted=0
	/*** CI4 Start - If reverse department is not specified, don't do anything ***/
	and da.DepartmentID<>0
	/*** CI4 END******************************************************************/
	/*** CID8 Start****************************************************************/
	and daf.IsDeleted=0
	/*** CID8 END******************************************************************/

UNION ALL

--Department Mapping (Direct)
select 
	da.OBAllocationID,
	dm.ExecutionOrder,
	fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, 
	da.DepartmentSourceID,
	fa.AccountID as AccountSourceID, 
	db2.DepartmentalBudgetID as DepartmentalBudgetTargetID,
	da.DepartmentTargetID,
	/*** START CID 3 ***********************************************/
	ta.AccountID as AccountTargetID,
	/*** END CID 3 *************************************************/
	fa.FiscalYearID, 
	fa.TimeClassId, 
	fa.UnitTypeID, 
	fa.DataTypeID,
	0 as isReverse,
	da.AllocationPercentage,
	fa.Month01*da.AllocationPercentage as Month01, 
	fa.Month02*da.AllocationPercentage as Month02,
	fa.Month03*da.AllocationPercentage as Month03,
	fa.Month04*da.AllocationPercentage as Month04,
	fa.Month05*da.AllocationPercentage as Month05,
	fa.Month06*da.AllocationPercentage as Month06,
	fa.Month07*da.AllocationPercentage as Month07,
	fa.Month08*da.AllocationPercentage as Month08,
	fa.Month09*da.AllocationPercentage as Month09,
	fa.Month10*da.AllocationPercentage as Month10,
	fa.Month11*da.AllocationPercentage as Month11,
	fa.Month12*da.AllocationPercentage as Month12,
	fa.Total*da.AllocationPercentage as Total
from 
	[clientob].[FactAccount] fa
	inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [clientob].[FactAllocationDepartmentMapping] da on db.DepartmentID=da.DepartmentSourceID 
	inner join [ob].[DimOBAllocation] dm on da.OBAllocationID=dm.OBAllocationID -- CID 10
	inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=da.DepartmentTargetID
	inner join [fw].[DimAccount] acc on fa.AccountID=acc.AccountID
	/*** START CID 3 ***********************************************/
	inner join [fw].[DimAccount] ta on ta.AccountID= case when da.AccountTargetID=0 then fa.AccountID else da.AccountTargetID end
	/*** END CID 3 *************************************************/
	inner join [clientob].[FactAllocationDepartmentMappingFilter] daf on daf.OBAllocationID=da.OBAllocationID and daf.FinancialReportingID=acc.OBDollarsFinancialReportingID	
where 
	fa.TimeClassID=2
	and fa.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
	and fa.Total<>0
	/*** CID9 Start****************************************************************/
	and fa.UnitTypeID=34
	/*** CID9 END******************************************************************/
	and da.IsDeleted=0
	/*** CID8 Start****************************************************************/
	and daf.IsDeleted=0
	/*** CID8 END******************************************************************/
GO


---------------------------------------------

-- ob.viewBudgetPlanStatus
create view ob.viewBudgetPlanStatus
as
    select
      d.DepartmentID,
      d.IsOB as IsDepartmentOB,
      d.IsActive as IsDepartmentActive,
      d.IsVariable as IsDepartmentVariable,
      cast(max(case when b.MemberGUID is null or p.PlanGUID is null then 0 else 1 end) as bit) as IsBudgetCreated,
      cast(max(case when isnull(mt.Name, 'n/a') = 'GM Blank' then 0 else 1 end) as bit) as IsBudgetActive
    from
      fw.DimDepartment d
      left join ob.DimDepartmentalBudget b on d.DepartmentID = b.DepartmentID
      left join dbo.XPlan p on p.PlanGUID = b.MemberGUID and p.IsDeletedPlan = 0
      left join dbo.EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID
	group by
		d.DepartmentID, 
		d.IsOB, 
		d.IsActive, 
		d.IsVariable
GO


---------------------------------------------

-- ob.viewDimAccountPH
CREATE VIEW [ob].[viewDimAccountPH]
AS
SELECT
   grp5927549978BB41F1B481CF9F6F7BFE67.[AccountPHID]
   ,grp5927549978BB41F1B481CF9F6F7BFE67.[Name]
   ,grp5927549978BB41F1B481CF9F6F7BFE67.[MemberGUID]
, [grp5927549978BB41F1B481CF9F6F7BFE67].[Version], [grp5927549978BB41F1B481CF9F6F7BFE67].[HistoryItemGUID]FROM [ob].[DimAccountPH] grp5927549978BB41F1B481CF9F6F7BFE67 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimAdjustmentCategory
--Last Modified 1/6/2017 4:38 PM
CREATE VIEW [ob].[viewDimAdjustmentCategory]
AS
SELECT
   grp0A9648AA978144AAA3E1A68E63558EDE.[AdjustmentCategoryID]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[Name]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[Description]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[AdjustmentCategoryRollup]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[BudgetConfigGUID]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[TransactionID]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[MemberGUID]
   ,grp0A9648AA978144AAA3E1A68E63558EDE.[HistoryItemGUID]
FROM [ob].[DimAdjustmentCategory] grp0A9648AA978144AAA3E1A68E63558EDE (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimDepartmentalBudget
CREATE VIEW [ob].[viewDimDepartmentalBudget]
AS
SELECT

[FrameworkID],
 COALESCE([Name],'') as [Name],
[LootID],
[DepartmentalBudgetID],
[DepartmentID],
 COALESCE([DepartmentName],'') as [DepartmentName],
[SystemID],
 COALESCE([System],'') as [System],
[SystemSortOrder],
[EntityID],
 COALESCE([Entity],'') as [Entity],
[EntitySortOrder],
[DepartmentRollup1ID],
 COALESCE([DepartmentRollup1],'') as [DepartmentRollup1],
[DepartmentRollup1SortOrder],
[DepartmentRollup2ID],
 COALESCE([DepartmentRollup2],'') as [DepartmentRollup2],
[DepartmentRollup2SortOrder],
[DepartmentRollup3ID],
 COALESCE([DepartmentRollup3],'') as [DepartmentRollup3],
[DepartmentRollup3SortOrder],
[DepartmentRollup4ID],
[GMTestFWName],
[GMTestFWDateCreated],
 COALESCE([DepartmentRollup4],'') as [DepartmentRollup4],
[DepartmentRollup4SortOrder],
[BaseYear],
[DepartmentRollup5ID],
 COALESCE([DepartmentRollup5],'') as [DepartmentRollup5],
[Director],
[DepartmentRollup5SortOrder],
[DepartmentRollup6ID],
[HasAttachments],
[LastModified],
 COALESCE([DepartmentRollup6],'') as [DepartmentRollup6],
[DepartmentRollup6SortOrder],
[Manager],
[MonthsLoaded],
[ResearchDepartmentCategoryID],
 COALESCE([ResearchDepartmentCategoryName],'') as [ResearchDepartmentCategoryName],
[OBActivePlans],
[OpenDate],
[ResearchDepartmentCategorySortOrder],
[IsVariable],
[MemberGUID],
[VicePresident],
[HistoryItemGUID],
[BaseYear1],
[BudgetStatus],
[WorkedHrsperUOSProjection],
[WorkedHrsperUOSBudget],
[FTEApprovalOverride],
[HourType],
[TargetType],
[Admin],
[Finance],
[ContractLaborSkillMix],
[StartYear],
[NumberofYears],
[VariableProjectionMethod],
[HideNotSpecified],
[HourTypeFixed],
[MRVicePresident],
[MRDirector],
[MRManager],
[ReadOnly],
[WriteDeny],
[EntityDefaultWorkWeekID],
[OBDirector],
[OBManager],
[OBVicePresident],
[SecureGroupID],
[VariablehrsperUOS],
[VariablehrsperUOStarget],
[BudgetedFixedFTEs],
[BudgetedVariableFTEs],
[UOSchangeyy],
[ExcessofRevandExpchangeyy],
[VariablehrsperUOSActualYTD],
[VariablehrsperUOStargetCurrentYr],
 COALESCE([DepartmentCode],'') as [DepartmentCode]    ,[Version]

FROM [ob].[DimDepartmentalBudget] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimDepartmentalBudgetPH_auto
CREATE VIEW [ob].[viewDimDepartmentalBudgetPH_auto]
AS
SELECT
   grpD3537B4CDBAB409B91F013D18B84C17C.[MemberGUID]
   ,grpD3537B4CDBAB409B91F013D18B84C17C.[DepartmentalBudgetPHID]
   ,grpD3537B4CDBAB409B91F013D18B84C17C.[Name]
   ,grpD3537B4CDBAB409B91F013D18B84C17C.[IsConstant]
, [grpD3537B4CDBAB409B91F013D18B84C17C].[Version], [grpD3537B4CDBAB409B91F013D18B84C17C].[HistoryItemGUID]FROM [ob].[DimDepartmentalBudgetPH] grpD3537B4CDBAB409B91F013D18B84C17C (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimDepartmentalBudget_source
CREATE VIEW [ob].[viewDimDepartmentalBudget_source]
AS
SELECT
   grp3321230B396444078881D601D47C5275.[DepartmentalBudgetID]
   ,grp3321230B396444078881D601D47C5275.[MemberGUID]
   ,grp3321230B396444078881D601D47C5275.[HistoryItemGUID]
   ,2 AS [FrameworkID]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [Name]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [DepartmentName]
   ,ISNULL([DEPT].[SystemID], 0) as [SystemID]
   ,ISNULL([DEPT].[System], 'Not Specified') as [System]
   ,ISNULL([DEPT].[SystemSortOrder], 0) as [SystemSortOrder]
   ,ISNULL([DEPT].[EntityID], 0) as [EntityID]
   ,ISNULL([DEPT].[Entity], 'Not Specified') as [Entity]
   ,ISNULL([DEPT].[EntitySortOrder], 0) as [EntitySortOrder]
   ,ISNULL([DEPT].[DepartmentRollup1ID], 0) as [DepartmentRollup1ID]
   ,ISNULL([DEPT].[DepartmentRollup1], 'Not Specified') as [DepartmentRollup1]
   ,ISNULL([DEPT].[DepartmentRollup1SortOrder], 0) as [DepartmentRollup1SortOrder]
   ,ISNULL([DEPT].[DepartmentRollup2ID], 0) as [DepartmentRollup2ID]
   ,ISNULL([DEPT].[DepartmentRollup2], 'Not Specified') as [DepartmentRollup2]
   ,ISNULL([DEPT].[DepartmentRollup2SortOrder], 0) as [DepartmentRollup2SortOrder]
   ,ISNULL([DEPT].[DepartmentRollup3ID], 0) as [DepartmentRollup3ID]
   ,ISNULL([DEPT].[DepartmentRollup3], 'Not Specified') as [DepartmentRollup3]
   ,ISNULL([DEPT].[DepartmentRollup3SortOrder], 0) as [DepartmentRollup3SortOrder]
   ,ISNULL([DEPT].[DepartmentRollup4ID], 0) as [DepartmentRollup4ID]
   ,ISNULL([DEPT].[DepartmentRollup4], 'Not Specified') as [DepartmentRollup4]
   ,ISNULL([DEPT].[DepartmentRollup4SortOrder], 0) as [DepartmentRollup4SortOrder]
   ,ISNULL([DEPT].[DepartmentRollup5ID], 0) as [DepartmentRollup5ID]
   ,ISNULL([DEPT].[DepartmentRollup5], 'Not Specified') as [DepartmentRollup5]
   ,ISNULL([DEPT].[DepartmentRollup5SortOrder], 0) as [DepartmentRollup5SortOrder]
   ,ISNULL([DEPT].[DepartmentRollup6ID], 0) as [DepartmentRollup6ID]
   ,ISNULL([DEPT].[DepartmentRollup6], 'Not Specified') as [DepartmentRollup6]
   ,ISNULL([DEPT].[DepartmentRollup6SortOrder], 0) as [DepartmentRollup6SortOrder]
   ,ISNULL([DEPT].[ResearchDepartmentCategoryID], 0) as [ResearchDepartmentCategoryID]
   ,ISNULL([DEPT].[ResearchDepartmentCategoryName], 'Not Specified') as [ResearchDepartmentCategoryName]
   ,ISNULL([DEPT].[ResearchDepartmentCategorySortOrder], 0) as [ResearchDepartmentCategorySortOrder]
   ,ISNULL([DEPT].[IsVariable], 0) as [IsVariable]
   ,ISNULL([DEPT].[WorkWeekID], 0) as [EntityDefaultWorkWeekID]
   ,ISNULL([DEPT].[SecureGroupID], 0) as [SecureGroupID]
   ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [DepartmentCode]
   ,ISNULL([DimXP].[PlanID], 0) as [LootID]
, [grp3321230B396444078881D601D47C5275].[Version]FROM [ob].[DimDepartmentalBudget] grp3321230B396444078881D601D47C5275 (readuncommitted)
   INNER JOIN [fw].[viewDimDepartment] [DEPT]  on [DEPT].[DepartmentID] = [grp3321230B396444078881D601D47C5275].[DepartmentID]
   INNER JOIN [fw].[viewDimXPlan_auto] [DimXP]  on [DimXP].[MemberGUID] = [grp3321230B396444078881D601D47C5275].[MemberGUID]
GO


---------------------------------------------

-- ob.viewDimExceptions
CREATE VIEW [ob].[viewDimExceptions]
AS
SELECT
   grpE6761F5FBF9A400B9432BFA871B53805.[OBExceptionsID]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[Name]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[Severity]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[Model]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[SortOrder]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[ViewName]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[TransactionID]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[MemberGUID]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[HistoryItemGUID]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[Description]
   ,grpE6761F5FBF9A400B9432BFA871B53805.[Resolution]
  ,coalesce(grpE6761F5FBF9A400B9432BFA871B53805.[FullName],'') as [FullName]
FROM [ob].[DimOBExceptions] grpE6761F5FBF9A400B9432BFA871B53805 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimFinancialReporting
CREATE VIEW [ob].[viewDimFinancialReporting]
AS
SELECT

[FinancialReportingID],
[Statement],
[Section],
[LineName],
 COALESCE([Name],'') as [Name],
[IsMappable],
[SortOrder],
[ConsolidatedFinancialReportingID],
[ConsolidatedIsInverted],
 COALESCE([StatementMappabilityFilterParameter],'') as [StatementMappabilityFilterParameter],
 COALESCE([ConsolidatedFinancialReporting],'') as [ConsolidatedFinancialReporting],
[ConsolidatedFinancialReportingSortOrder],
[ConsolidatedInversion],
[DisplayFormat],
[IsExpense],
[IsRequired],
[IsVolume],
[IsFTERollup],
[IsEditable],
[MemberGUID],
[HistoryItemGUID],
 COALESCE([ProjectionMethod],'') as [ProjectionMethod],
 COALESCE([SpreadMethod],'') as [SpreadMethod]
FROM [ob].[DimFinancialReporting] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimFinancialReportingPH
CREATE VIEW [ob].[viewDimFinancialReportingPH]
AS
SELECT
   grp6BAC2BD76D3C4C249EA077E4A3B60870.[FinancialReportingPHID]
   ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[Name]
   ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[MemberGUID]
   ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[HistoryItemGUID]
FROM [ob].[DimFinancialReportingPH] grp6BAC2BD76D3C4C249EA077E4A3B60870 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimFinancialReporting_source
CREATE VIEW [ob].[viewDimFinancialReporting_source]
AS
SELECT
   grp54CF5FA828E84C28B9227B92B8090EEE.[FinancialReportingID]
   ,grp54CF5FA828E84C28B9227B92B8090EEE.[ConsolidatedInversion]
   ,grp54CF5FA828E84C28B9227B92B8090EEE.[MemberGUID]
   ,grp54CF5FA828E84C28B9227B92B8090EEE.[HistoryItemGUID]
   ,grp54CF5FA828E84C28B9227B92B8090EEE.[ProjectionMethod]
   ,grp54CF5FA828E84C28B9227B92B8090EEE.[SpreadMethod]
   ,[grp54CF5FA828E84C28B9227B92B8090EEE].[Statement] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[Section] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[LineName] AS [Name]
   ,[grp54CF5FA828E84C28B9227B92B8090EEE].[Statement] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[IsMappable] AS [StatementMappabilityFilterParameter]
   ,ISNULL([CONSFINREP].[Name], 'Not Specified') as [ConsolidatedFinancialReporting]
   ,ISNULL([CONSFINREP].[SortOrder], 0) as [ConsolidatedFinancialReportingSortOrder]
FROM [ob].[DimFinancialReporting] grp54CF5FA828E84C28B9227B92B8090EEE (readuncommitted)
   INNER JOIN [fw].[viewDimConsolidatedFinancialReporting] [CONSFINREP]  on [CONSFINREP].[ConsolidatedFinancialReportingID] = [grp54CF5FA828E84C28B9227B92B8090EEE].[ConsolidatedFinancialReportingID]
GO


---------------------------------------------

-- ob.viewDimGlobalStatisticRollup
CREATE VIEW [ob].[viewDimGlobalStatisticRollup]
AS
SELECT
   grp720F3737CE7D4C0691B695FFCF7BA929.[StatisticRollupID]
   ,grp720F3737CE7D4C0691B695FFCF7BA929.[Name]
   ,grp720F3737CE7D4C0691B695FFCF7BA929.[MemberGUID]
FROM [ob].[DimGlobalStatisticRollup] grp720F3737CE7D4C0691B695FFCF7BA929 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimGlobalStatisticsPlanPH
CREATE VIEW [ob].[viewDimGlobalStatisticsPlanPH]
AS
SELECT
   grpC6B7D58A47914B2BB0BDDE89ABBD2900.[OBGlobalStatsPlanPHID]
   ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[Name]
   ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[MemberGUID]
   ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[HistoryItemGUID]
FROM [ob].[DimGlobalStatisticsPlanPH] grpC6B7D58A47914B2BB0BDDE89ABBD2900 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBAllocation
--Last Modified 2/26/2016 5:46 PM
CREATE VIEW [ob].[viewDimOBAllocation]
AS
SELECT
   grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[OBAllocationID]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[Name]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[Type]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[OBAllocationBasisID]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[AlwaysUseBasis]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[TransactionID]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[MemberGUID]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[HistoryItemGUID]
   ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[ExecutionOrder]
   ,ISNULL([OBALLOCATIONBASIS].[Name], 'Not Specified') as [AllocationBasisName]
FROM [ob].[DimOBAllocation] grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB (readuncommitted)
   INNER JOIN [ob].[viewDimOBAllocationBasis] [OBALLOCATIONBASIS]  on [OBALLOCATIONBASIS].[OBAllocationBasisID] = [grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB].[OBAllocationBasisID]
GO


---------------------------------------------

-- ob.viewDimOBAllocationBasis
CREATE VIEW [ob].[viewDimOBAllocationBasis]
AS
SELECT
   grpC089980B2C6046C1842FCC918B7F4A76.[OBAllocationBasisID]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[Name]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[TransactionID]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[OBForecastDetailID]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[MemberGUID]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[HistoryItemGUID]
   ,grpC089980B2C6046C1842FCC918B7F4A76.[Category]
FROM [ob].[DimOBAllocationBasis] grpC089980B2C6046C1842FCC918B7F4A76 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBForecastDetail
CREATE VIEW [ob].[viewDimOBForecastDetail]
AS
SELECT

[OBForecastDetailID],
[Category],
[Name],
[SortOrder],
[UnitTypeID],
 COALESCE([UnitType],'') as [UnitType],
[DriverID],
 COALESCE([Driver],'') as [Driver],
[IsSalaryDriver],
[IsRevenueDriver],
[AccountID],
 COALESCE([Account],'') as [Account],
[SecondaryAccountID],
 COALESCE([SecondaryAccount],'') as [SecondaryAccount],
[TransactionID],
[MemberGUID],
[HistoryItemGUID],
[Code],
[ForecastDetailRollup],
[VolumeTarget],
[IsMROnly],
[IsVariable]
FROM [ob].[DimOBForecastDetail] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBForecastDetailDriver
CREATE VIEW [ob].[viewDimOBForecastDetailDriver] as
select 
	OBForecastDetailID as OBForecastDetailDriverSelectionID,
	Name,
	MemberGUID,
	HistoryItemGUID,
	TransactionID
from [ob].[DimOBForecastDetail]
GO


---------------------------------------------

-- ob.viewDimOBForecastDetailDriver_auto
CREATE VIEW [ob].[viewDimOBForecastDetailDriver_auto]
AS
SELECT
   grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[OBForecastDetailDriverSelectionID]
   ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[Name]
   ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[HistoryItemGUID]
   ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[MemberGUID]
   ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[TransactionID]
FROM [ob].[viewDimOBForecastDetailDriver] grp95352FFAD8B04CA0A70AE8BBCB6CF67D
GO


---------------------------------------------

-- ob.viewDimOBForecastDetailPH
CREATE VIEW [ob].[viewDimOBForecastDetailPH]
AS
SELECT
   grp73D1EC9F68144CC1BCDC23C23514DA13.[OBForecastDetailPHID]
   ,grp73D1EC9F68144CC1BCDC23C23514DA13.[Name]
   ,grp73D1EC9F68144CC1BCDC23C23514DA13.[MemberGUID]
   ,grp73D1EC9F68144CC1BCDC23C23514DA13.[HistoryItemGUID]
   ,grp73D1EC9F68144CC1BCDC23C23514DA13.[TransactionID]
FROM [ob].[DimOBForecastDetailPH] grp73D1EC9F68144CC1BCDC23C23514DA13 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBForecastDetail_source
CREATE VIEW [ob].[viewDimOBForecastDetail_source]
AS
SELECT
   grpEEE051AAC24A4A73A3160CBD21350A21.[OBForecastDetailID]
   ,grpEEE051AAC24A4A73A3160CBD21350A21.[TransactionID]
   ,grpEEE051AAC24A4A73A3160CBD21350A21.[MemberGUID]
   ,grpEEE051AAC24A4A73A3160CBD21350A21.[HistoryItemGUID]
   ,ISNULL([UNITTYPE].[Name], 'Not Specified') as [UnitType]
   ,ISNULL([viewDimOBFor].[Name], 'Not Specified') as [Driver]
   ,ISNULL([ACCT].[Name], 'Not Specified') as [Account]
   ,ISNULL([ACCT_1].[Name], 'Not Specified') as [SecondaryAccount]
FROM [ob].[DimOBForecastDetail] grpEEE051AAC24A4A73A3160CBD21350A21 (readuncommitted)
   INNER JOIN [fw].[viewDimUnitType] [UNITTYPE]  on [UNITTYPE].[UnitTypeID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[UnitTypeID]
   INNER JOIN [ob].[viewDimOBForecastDetailDriver_auto] [viewDimOBFor]  on [viewDimOBFor].[OBForecastDetailDriverSelectionID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[DriverID]
   INNER JOIN [fw].[viewDimAccount] [ACCT]  on [ACCT].[AccountID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[AccountID]
   INNER JOIN [fw].[viewDimAccount] [ACCT_1]  on [ACCT_1].[AccountID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[SecondaryAccountID]
GO


---------------------------------------------

-- ob.viewDimOBGlobalStatistics
CREATE VIEW [ob].[viewDimOBGlobalStatistics]
AS
SELECT

 COALESCE([Name],'') as [Name],
[OBGlobalStatisticID],
[TransactionID],
[MemberGUID],
[HistoryItemGUID],
 COALESCE([AccountDescription],'') as [AccountDescription],
 COALESCE([AccountCode],'') as [AccountCode],
[AccountID],
 COALESCE([DepartmentCode],'') as [DepartmentCode],
 COALESCE([Account],'') as [Account],
[DepartmentID],
 COALESCE([Department],'') as [Department],
[OBForecastDetailID],
 COALESCE([OBForecastDetail],'') as [OBForecastDetail],
[LOSLinkID],
 COALESCE([LOSLink],'') as [LOSLink],
 COALESCE([PatientClass],'') as [PatientClass],
 COALESCE([OBPayor],'') as [OBPayor],
 COALESCE([OBPayorGroup],'') as [OBPayorGroup],
 COALESCE([OBUnitsFinancialReportingName],'') as [OBUnitsFinancialReportingName],
 COALESCE([OBUnitsFinancialReportingLineName],'') as [OBUnitsFinancialReportingLineName],
 COALESCE([FillinSection],'') as [FillinSection]
FROM [ob].[DimOBGlobalStatistics] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBGlobalStatisticsPH
CREATE VIEW [ob].[viewDimOBGlobalStatisticsPH]
AS
SELECT
   grp859651793B9E4DC5A841C41AD656A89C.[OBGlobalStatisticsPHID]
   ,grp859651793B9E4DC5A841C41AD656A89C.[Name]
   ,grp859651793B9E4DC5A841C41AD656A89C.[MemberGUID]
   ,grp859651793B9E4DC5A841C41AD656A89C.[HistoryItemGUID]
   ,grp859651793B9E4DC5A841C41AD656A89C.[TransactionID]
FROM [ob].[DimOBGlobalStatisticsPH] grp859651793B9E4DC5A841C41AD656A89C (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBGlobalStatisticsPlan
CREATE VIEW [ob].[viewDimOBGlobalStatisticsPlan]
AS
SELECT

[OBGlobalStatisticsPlanID],
[Name],
[EntityID],
 COALESCE([Entity],'') as [Entity],
[LootID],
[IsDeleted],
[HistoryItemGUID],
[MemberGUID],
[TransactionID],
[SecureGroupID],
[BaseYear],
[MonthsLoaded],
[StartYear],
[NumberofYears],
[FrameworkID]
FROM [ob].[DimOBGlobalStatisticsPlan] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBGlobalStatisticsPlan_source
CREATE VIEW [ob].[viewDimOBGlobalStatisticsPlan_source]
AS
SELECT
   grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[OBGlobalStatisticsPlanID]
   ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[HistoryItemGUID]
   ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[MemberGUID]
   ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[TransactionID]
   ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[SecureGroupID]
   ,2 AS [FrameworkID]
   ,ISNULL([ENT].[Name], 'Not Specified') as [Entity]
   ,ISNULL([DimXP].[PlanID], 0) as [LootID]
   ,ISNULL([DimXP].[IsDeleted], 0) as [IsDeleted]
FROM [ob].[DimOBGlobalStatisticsPlan] grp5CAD0D676A7C4C8D80A34AAB99E6C79D (readuncommitted)
   INNER JOIN [fw].[viewDimEntity] [ENT]  on [ENT].[EntityID] = [grp5CAD0D676A7C4C8D80A34AAB99E6C79D].[EntityID]
   INNER JOIN [fw].[viewDimXPlan_auto] [DimXP]  on [DimXP].[MemberGUID] = [grp5CAD0D676A7C4C8D80A34AAB99E6C79D].[MemberGUID]
GO


---------------------------------------------

-- ob.viewDimOBGlobalStatistics_source
CREATE VIEW [ob].[viewDimOBGlobalStatistics_source]
AS
SELECT
   grpEDB4F13AA36044A48FFB77C37AFA87F5.[Name]
   ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[OBGlobalStatisticID]
   ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[TransactionID]
   ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[MemberGUID]
   ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[HistoryItemGUID]
   ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[FillinSection]
   ,ISNULL([ACCT].[Description], 'Not Specified') as [AccountDescription]
   ,ISNULL([ACCT].[AccountCode], 'Not Specified') as [AccountCode]
   ,ISNULL([ACCT].[Name], 'Not Specified') as [Account]
   ,ISNULL([ACCT].[PatientClass], 'Not Specified') as [PatientClass]
   ,ISNULL([ACCT].[OBPayor], 'Not Specified') as [OBPayor]
   ,ISNULL([ACCT].[OBPayorGroup], 'Not Specified') as [OBPayorGroup]
   ,ISNULL([ACCT].[OBUnitsFinancialReporting], 'Not Specified') as [OBUnitsFinancialReportingName]
   ,ISNULL([ACCT].[OBUnitsFinancialReportingLineName], 'Not Specified') as [OBUnitsFinancialReportingLineName]
   ,ISNULL([ACCT_1].[Name], 'Not Specified') as [LOSLink]
   ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [DepartmentCode]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [Department]
   ,ISNULL([OBFORECASTDETAIL].[Name], 'Not Specified') as [OBForecastDetail]
FROM [ob].[DimOBGlobalStatistics] grpEDB4F13AA36044A48FFB77C37AFA87F5 (readuncommitted)
   INNER JOIN [fw].[viewDimAccount] [ACCT]  on [ACCT].[AccountID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[AccountID]
   INNER JOIN [fw].[viewDimAccount] [ACCT_1]  on [ACCT_1].[AccountID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[LOSLinkID]
   INNER JOIN [fw].[viewDimDepartment] [DEPT]  on [DEPT].[DepartmentID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[DepartmentID]
   INNER JOIN [ob].[viewDimOBForecastDetail] [OBFORECASTDETAIL]  on [OBFORECASTDETAIL].[OBForecastDetailID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[OBForecastDetailID]
GO


---------------------------------------------

-- ob.viewDimOBReimbursementPlan
CREATE VIEW [ob].[viewDimOBReimbursementPlan]
AS
SELECT

[OBReimbursementPlanID],
[Name],
[MemberGUID],
[HistoryItemGUID],
[LootID],
[FrameworkID],
[EntityID],
 COALESCE([Entity],'') as [Entity],
[EntitySortOrder],
[NameCalc],
[BaseYear],
[StartYear],
[NumberofYears],
[SecureGroupID],
[MonthsLoaded]
FROM [ob].[DimOBReimbursementPlan] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBReimbursementPlanPH
CREATE VIEW [ob].[viewDimOBReimbursementPlanPH]
AS
SELECT
   grpAC3B5D29356247F5BDDFCFC8D09E9F17.[OBReimbursementPlanPHID]
   ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[Name]
   ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[MemberGUID]
   ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[HistoryItemGUID]
FROM [ob].[DimOBReimbursementPlanPH] grpAC3B5D29356247F5BDDFCFC8D09E9F17 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBReimbursementPlan_source
CREATE VIEW [ob].[viewDimOBReimbursementPlan_source]
AS
SELECT
   grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[OBReimbursementPlanID]
   ,grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[MemberGUID]
   ,grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[HistoryItemGUID]
   ,2 AS [FrameworkID]
   ,ISNULL([DimXP].[PlanID], 0) as [LootID]
   ,ISNULL([ENT].[Name], 'Not Specified') as [Entity]
   ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder]
   ,ISNULL([ENT].[SecureGroupID], 0) as [SecureGroupID]
FROM [ob].[DimOBReimbursementPlan] grpBCD22BB1EBDC4C07A9DB2AB6AB061F79 (readuncommitted)
   INNER JOIN [fw].[viewDimXPlan_auto] [DimXP]  on [DimXP].[MemberGUID] = [grpBCD22BB1EBDC4C07A9DB2AB6AB061F79].[MemberGUID]
   INNER JOIN [fw].[viewDimEntity] [ENT]  on [ENT].[EntityID] = [grpBCD22BB1EBDC4C07A9DB2AB6AB061F79].[EntityID]
GO


---------------------------------------------

-- ob.viewDimOBServiceLinePlan
CREATE VIEW [ob].[viewDimOBServiceLinePlan]
AS
SELECT

[OBServiceLinePlanID],
[EntityID],
[Name],
[FrameworkID],
[LootID],
[IsDeleted],
 COALESCE([Entity],'') as [Entity],
[EntitySortOrder],
[SecureGroupID],
[TransactionID],
[MemberGUID],
[HistoryItemGUID],
[BaseYear],
[MonthsLoaded],
[StartYear],
[NumberofYears],
[InpatientVolumeBudgetYear],
[ClinicVolumeBudgetYear],
[ClinicVolumeProjectedYear],
[EDVolumeBudgetYear],
[EDVolumeProjectedYear],
[InpatientVolumeProjectedYear],
[ObservationVolumeBudgetYear],
[ObservationVolumeProjectedYear],
[OtherVolumeBudgetYear],
[OtherVolumeProjectedYear],
[OutpatientVolumeBudgetYear],
[OutpatientVolumeProjectedYear]
FROM [ob].[DimOBServiceLinePlan] (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBServiceLinePlanPH
CREATE VIEW [ob].[viewDimOBServiceLinePlanPH]
AS
SELECT
   grpCA35C88C6A9A4080B0FF5FBA968C28A7.[OBServiceLinePlanPHID]
   ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[Name]
   ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[MemberGUID]
   ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[HistoryItemGUID]
   ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[TransactionID]
FROM [ob].[DimOBServiceLinePlanPH] grpCA35C88C6A9A4080B0FF5FBA968C28A7 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimOBServiceLinePlan_source
CREATE VIEW [ob].[viewDimOBServiceLinePlan_source]
AS
SELECT
   grp69AF13389B5C41B5A4367BD2A516074B.[OBServiceLinePlanID]
   ,grp69AF13389B5C41B5A4367BD2A516074B.[TransactionID]
   ,grp69AF13389B5C41B5A4367BD2A516074B.[MemberGUID]
   ,grp69AF13389B5C41B5A4367BD2A516074B.[HistoryItemGUID]
   ,2 AS [FrameworkID]
   ,ISNULL([ENT].[Name], 'Not Specified') as [Entity]
   ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder]
   ,ISNULL([ENT].[SecureGroupID], 0) as [SecureGroupID]
   ,ISNULL([DimXP].[PlanID], 0) as [LootID]
   ,ISNULL([DimXP].[IsDeleted], 0) as [IsDeleted]
FROM [ob].[DimOBServiceLinePlan] grp69AF13389B5C41B5A4367BD2A516074B (readuncommitted)
   INNER JOIN [fw].[viewDimEntity] [ENT]  on [ENT].[EntityID] = [grp69AF13389B5C41B5A4367BD2A516074B].[EntityID]
   INNER JOIN [fw].[viewDimXPlan_auto] [DimXP]  on [DimXP].[MemberGUID] = [grp69AF13389B5C41B5A4367BD2A516074B].[MemberGUID]
GO


---------------------------------------------

-- ob.viewDimOBSnapshot
CREATE VIEW [ob].[viewDimOBSnapshot]
AS
SELECT
   grp39C103E65DEC41F09D8D6D4E85A82692.[OBSnapshotID]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[Name]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[TransactionID]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[MemberGUID]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[HistoryItemGUID]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[Category]
   ,grp39C103E65DEC41F09D8D6D4E85A82692.[Date]
FROM [ob].[DimOBSnapshot] grp39C103E65DEC41F09D8D6D4E85A82692 (readuncommitted)
GO


---------------------------------------------

-- ob.viewDimSpread
--Last Modified 5/25/2018 10:33 AM
CREATE VIEW [ob].[viewDimSpread]
AS
SELECT
   grp70A27E28D45145339A6384110B97E4B3.[SpreadID]
   ,grp70A27E28D45145339A6384110B97E4B3.[Name]
   ,grp70A27E28D45145339A6384110B97E4B3.[MemberGUID]
   ,grp70A27E28D45145339A6384110B97E4B3.[IsBuiltIn]
   ,grp70A27E28D45145339A6384110B97E4B3.[SortOrder]
  ,coalesce(grp70A27E28D45145339A6384110B97E4B3.[Category],'') as [Category]
FROM [ob].[DimSpread] grp70A27E28D45145339A6384110B97E4B3 (readuncommitted)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetAccountsNotBudgeted
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetAccountsNotBudgeted]
AS
SELECT 
    DB.[DepartmentalBudgetID], 
    DB.[Name] AS Model, 
    'Has ' + CAST(CAST(SUM(FA.[Total]) AS DECIMAL(16,2)) AS NVARCHAR(100)) + ' current year ' + UT.[Name] + ' for Account ' + ACC.[Name] + ' but does not have a budget.' AS [Detail]
FROM [clientob].[FactAccount] AS FA
    INNER JOIN [fw].[DimUnitType] AS UT
        ON FA.[UnitTypeID] = UT.[UnitTypeID]
    INNER JOIN [fw].[DimAccount] AS ACC
        ON ACC.[AccountID] = FA.[AccountID]
    INNER JOIN [ob].[DimDepartmentalBudget] AS DB
        ON DB.[DepartmentalBudgetID] = FA.[DepartmentalBudgetID]
WHERE 1=1
    AND FA.[IsDeleted] IN (0, 1)
    AND FA.[FiscalYearID] = (SELECT TOP 1 CAST([Setting] AS INT) FROM [dbo].[DBSetting] WHERE [DBSettingGUID] = '9c921c27-f3e4-4616-b3fd-925a75870b62')
    AND FA.[TimeClassID] = 1 -- Actual
    AND FA.[Total] <> 0
    AND ACC.[AccountID] <> 0
    AND NOT (ACC.[OBIsDefined] = 1 AND ACC.[OBAccountPHID] = 0 AND ACC.[OBStatModelSectionID] = 0)
    AND UT.[UnitTypeID] IN (34, 51, 140) -- Dollars, Volume and Hours (contract labor)
    AND DB.[OBActivePlans] = '1'
    AND NOT EXISTS 
        (
            SELECT
                1
            FROM [clientob].[FactAccount] AS FA2
            WHERE 1 = 1
                AND FA2.[DepartmentalBudgetID] = FA.[DepartmentalBudgetID] 
                AND FA2.[AccountID] = FA.[AccountID]
                AND FA2.[UnitTypeID] = FA.[UnitTypeID]
                AND FA2.[TimeClassID] = 2 -- Budgeted
                AND FA2.[FiscalYearID] = FA.[FiscalYearID] + 1
                AND FA2.[IsDeleted] IN (0, 1)
                AND FA2.[Total] <> 0
          )
GROUP BY
    DB.[DepartmentalBudgetID], 
    DB.[Name],
    UT.[Name],
    ACC.[Name]
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetActiveButNoHistory
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all budgets that are set to active but have no current year activity
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetActiveButNoHistory] as
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is set to Active but no current year account activity'  as Detail
from [ob].[DimDepartmentalBudget] db with (readuncommitted) 
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and db.DepartmentalBudgetID not in (
	select fct1.DepartmentalBudgetID from [clientob].[FactAccount] fct1 with (readuncommitted)
	inner join [ob].[DimDepartmentalBudget] db1  with (readuncommitted) on fct1.DepartmentalBudgetID=db1.DepartmentalBudgetID and fct1.FiscalYearID=db1.BaseYear
	where fct1.TimeClassID in (1,2) and fct1.Total<>0 and DataTypeID=4
)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetContractLaborDollarsWithoutHours
/************************************************************
** Author: mschmitz
** Create Date: 2015-01-18
** Description: Checks for departmental budgets that have contract labor dollars without hours in historic time periods
** Last Modified: 2016-11-30
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI				Description
** 1		2016-11-30	srk			D-04692		Updated exception report to look for historic time periods where there are dollars but no hours, 
**														instead of looking for budgeted dollars without hours. It works similar the job code with dollars 
**														but no hours exception now.
**
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetContractLaborDollarsWithoutHours] AS

SELECT DISTINCT
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has dollars but no hours for contract labor account ' + DA.Name + ' in ' + tc.name + ' '+ cast(FA.FiscalYearID as char(4)) as 'Detail'
FROM [clientob].[FactAccount] FA with (readuncommitted) 
	INNER JOIN [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID=FA.DepartmentalBudgetID
	INNER JOIN [fw].[DimAccount] DA with (readuncommitted) on DA.AccountID = FA.AccountID
	INNER JOIN [data].[ScoreFillin_Account] SFA on FA.AccountID = SFA.AccountID
	INNER JOIN [ob].[DimAccountPH] PH on SFA.PlaceholderSectionMemberGUID = PH.MemberGUID 
	INNER JOIN [fw].[DimTimeClass] TC on FA.TimeClassID = TC.TimeClassID
		and PH.Name = 'Staffing - Contract Labor'
WHERE 1=1
	and FA.UnitTypeID=34
	and FA.Total != 0
	and FA.DataTypeID = 4 -- Input
	and FA.TimeClassID = 1 -- Budget
	and FA.FiscalYearID <= (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists
	(
	SELECT top 1 1
	FROM [clientob].[FactAccount] FA1 with (readuncommitted) 
	WHERE 1=1
		and FA1.UnitTypeID in 
			(
				51 --hours
				,146 --nonproductive
				,147 --differential
				,148 --productive
			)
		and FA1.DepartmentalBudgetID=FA.DepartmentalBudgetID
		and FA1.AccountID = FA.AccountID
		and FA1.FiscalYearID = FA.FiscalYearID
		and FA1.DataTypeID = 4 -- Input
		and FA1.TimeClassID = 1 -- Actual
		and FA1.Total != 0
	)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetDataWithoutDimensionMembers
/************************************************************
** Author: jgerber
** Create Date: 2014-09-17
** Description: Checks for dept budget data that does not have dimension members 
** Last Modified: 2014-09-17
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

create view [ob].[viewExceptionsDepartmentBudgetDataWithoutDimensionMembers] as

--***Fact Account*********************************************
-- Department Dimension
	select
		Distinct
		0 as DepartmentalBudgetID,
		'Not Specified' as Model,
		'Has General Ledger data for a Department that no longer exists' as Detail
	from 
		[clientob].[FactAccount] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Account Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has General Ledger data for an Account that no longer exists' as Detail
	from 
		[clientob].[FactAccount] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID
	where 
		dim.MemberGUID is null	
		
UNION ALL		
		
--***Fact Staffing PC*********************************************
-- Department Dimension
	select
		Distinct
		0 as DepartmentalBudgetID,
		'Not Specified' as Model,
		'Has Staffing data for a Department that no longer exists' as Detail
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
Union ALL	
		
-- Job Code Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Staffing data for a Job Code that no longer exists' as Detail
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimJobCode] dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID
	where 
		dim.MemberGUID is null			
		
Union ALL	
		
-- Pay Code Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Staffing data for a Pay Code that no longer exists' as Detail
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimPayCode] dim with (readuncommitted) on dim.PayCodeID = data.PayCodeID
	where 
		dim.MemberGUID is null			
		
Union ALL	
		
-- Pay Code Group Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Staffing data for a Pay Code Group that no longer exists' as Detail
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimPayCodeGroup] dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID
	where 
		dim.MemberGUID is null			
		
Union ALL	
		
-- Employee Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Staffing data for a Employee that no longer exists' as Detail
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimEmployee] dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID
	where 
		dim.MemberGUID is null				
		
UNION ALL		
		
--***Fact Provider*********************************************
-- Department Dimension
	select
		Distinct
		0 as DepartmentalBudgetID,
		'Not Specified' as Model,
		'Has Provider data for a Department that no longer exists' as Detail
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Provider Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Provider data for a Provider that no longer exists' as Detail
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimProvider] dim with (readuncommitted) on dim.ProviderID = data.ProviderID
	where 
		dim.MemberGUID is null			
		
UNION ALL	
		
-- Forecast Detail Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Provider data for a Forecast Detail that no longer exists' as Detail
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null			
		
UNION ALL		
		
--***Fact Charge Code*********************************************
-- Department Dimension
	select
		Distinct
		0 as DepartmentalBudgetID,
		'Not Specified' as Model,
		'Has Charge Code data for a Department that no longer exists' as Detail
	from 
		[clientob].[FactCDM] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Charge Code Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Charge Code data for a Charge Code that no longer exists' as Detail
	from 
		[clientob].[FactCDM] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimChargeCode] dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID
	where 
		dim.MemberGUID is null			
				
UNION ALL 

--***Fact Reporting*********************************************
-- Department Dimension
	select
		Distinct
		0 as DepartmentalBudgetID,
		'Not Specified' as Model,
		'Has Financial Reporting data for a Department that no longer exists' as Detail
	from 
		[clientob].[FactReportingMonthly] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Financial Reporting Dimension
	select
		Distinct
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has Financial Reporting data for a Line Item that no longer exists' as Detail
	from 
		[clientob].[FactReportingMonthly] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [ob].[DimFinancialReporting] dim with (readuncommitted) on dim.FinancialReportingID = data.FinancialReportingID
	where 
		dim.MemberGUID is null
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetDollarsWithoutHours
/************************************************************
** Author: mschmitz
** Create Date: 2015-01-18
** Description: Checks for job code/pay code group combos that have dollars but not hours in historic time periods
** Last Modified: 08/01/2017
** GM Release: 2017.2
**************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI			Description
** 1		08/04/2015		CBB			D-03150		Issues with false positives - Rebuilt using structure from BudgetHoursWithoutDollars
** 2		09/19/2016		BL			D-04355		Filter out "Dollars Only" Productive Class from exception
** 3		10/26/2016		GF			B-13254		Refactored for performance
** 4		2017-02-10		akk			D-05381		Adding productive non-fte unit type to hours subquery
** 5      08/01/2017      vyaremko   D-06199      Filter out inactive departments
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetDollarsWithoutHours] 
AS
	SELECT DISTINCT
		DB.[DepartmentalBudgetID] AS [DepartmentalBudgetID],
		DB.[Name] AS [Model],
		'Has dollars in pay code group '
			+ PCG.[Name]
			+ ' but no hours for job code '
			+ JC.[Name]
			+ ' in '
			+ TC.[Name]
			+ ' '
			+ cast(st.FiscalYearID as char(4))
			AS [Detail]
		,TC.[Name]
		,ST.[FiscalYearID]
	FROM [clientob].[FactStaffingPC] AS ST WITH (READUNCOMMITTED) 
		INNER JOIN [ob].[DimDepartmentalBudget] AS DB WITH (READUNCOMMITTED)
            ON DB.[DepartmentalBudgetID] = ST.[DepartmentalBudgetID]
		INNER JOIN [fw].[DimJobCode] AS JC WITH (READUNCOMMITTED)
            ON JC.[JobCodeID] = ST.[JobCodeID]
		INNER JOIN [fw].[DimPayCodeGroup] AS PCG WITH (READUNCOMMITTED)
            ON PCG.[PayCodeGroupID] = ST.[PayCodeGroupID]
		INNER JOIN [fw].[DimTimeClass] AS TC WITH (READUNCOMMITTED)
            ON TC.[TimeClassID] = ST.[TimeClassID]
	WHERE 1=1
		AND ST.[UnitTypeID] = 34
		AND PCG.[ProductiveClassID] <> 4 
		AND ST.[Total] != 0
		AND DB.[OBActivePlans] = '1'
		AND NOT EXISTS(
			SELECT 1
			FROM [clientob].[FactStaffingPC] AS H WITH (READUNCOMMITTED) 
			WHERE 1=1
				AND H.[UnitTypeID] IN 
				(
					 51 --hours
					,146 --nonproductive
					,147 --differential
					,148 --productive
					,52 --productive non-fte
				)
				AND H.[DepartmentalBudgetID] = ST.[DepartmentalBudgetID]
				AND H.[DataTypeID] = ST.[DataTypeID]
				AND H.[FiscalYearID] = ST.[FiscalYearID]
				AND H.[JobCodeID] = ST.[JobCodeID]
				AND H.[PayCodeGroupID] = ST.[PayCodeGroupID]
				AND H.[TimeClassID] = ST.[TimeClassID]
				AND H.[Total] != 0
		);
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetDuplicateFillins
/************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: Finds all duplicate fillins in the OB Departmental Budget model for the Account, Employee, Job Code, and Pay Code Group dimensions
** Last Modified: 2013-10-07
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-10-07	JG				Renaming and adding to the exception summary report 
**
*************************************************************/

create view [ob].[viewExceptionsDepartmentBudgetDuplicateFillins] as

--ACCOUNTS
--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS

select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail

from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID
	inner join
(
select
	distinct DB.DepartmentalBudgetID, FI1.AccountID
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID
	inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
		and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID
where
	exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) 
	inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID
	inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID
	where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID
	and ME2.ExclusivityGroup=me.ExclusivityGroup)
	and ME.IsExclusive = 1 
) DUPES
	on DB.DepartmentalBudgetID = DUPES.DepartmentalBudgetID
	and DIM.AccountID = DUPES.AccountID
	and PH.AccountPHID<>0
	

union all

--EMPLOYEE
-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' in section ' + PH1.Name + ' is also in another section' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_Employee FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join fw.DimEmployeePH PH1 with (readuncommitted) on FI1.EmployeePHID = PH1.EmployeePHID
	inner join fw.DimEmployee DIM with (readuncommitted) on FI1.EmployeeID = DIM.EmployeeID
where
	PH1.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)')
	and exists
(select 1
from
	data.ScoreFillin_Employee FI2 with (readuncommitted)
	inner join fw.DimEmployeePH PH2 with (readuncommitted) on FI2.EmployeePHID = PH2.EmployeePHID
where
	PH2.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)')
	and FI1.ModelGUID = FI2.ModelGUID
	and FI1.EmployeeID = FI2.EmployeeID
	and FI1.EmployeePHID != FI2.EmployeePHID
)

union all

--JOB CODE
-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' in section ' + PH1.Name + ' is also in another section' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_JobCode FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join fw.DimJobCodePH PH1 with (readuncommitted) on FI1.JobCodePHID= PH1.JobCodePHID
	inner join fw.DimJobCode DIM with (readuncommitted) on FI1.JobCodeID = DIM.JobCodeID
where
	PH1.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)')
	and exists
(select 1
from
	data.ScoreFillin_JobCode FI2 with (readuncommitted)
	inner join fw.DimJobCodePH PH2 with (readuncommitted) on FI2.JobCodePHID = PH2.JobCodePHID
where
	PH2.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)')
	and FI1.ModelGUID = FI2.ModelGUID
	and FI1.JobCodeID = FI2.JobCodeID
	and FI1.JobCodePHID != FI2.JobCodePHID
)

union all

--OB FINANCIAL REPORTING
-- CHECK IF FINANCIAL REPORTING SHOWS UP IN MORE THAN ONE SECTION
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_OBFinancialReporting FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI1.FinancialReportingPHID= PH.FinancialReportingPHID
	inner join ob.DimFinancialReporting DIM with (readuncommitted) on FI1.FinancialReportingID = DIM.FinancialReportingID
where exists
(select 1
from
	data.ScoreFillin_FinancialReporting FI2 with (readuncommitted)
where
	FI1.ModelGUID = FI2.ModelGUID
	and FI1.FinancialReportingID= FI2.FinancialReportingID
	and FI1.FinancialReportingPHID!= FI2.FinancialReportingPHID
)
and PH.FinancialReportingPHID<>0

union all

--PAY CODE GROUP
--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_PayCodeGroup FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID
	inner join fw.DimPayCodeGroup DIM with (readuncommitted) on FI.PayCodeGroupID = DIM.PayCodeGroupID
	inner join
(
select
	distinct DB.DepartmentalBudgetID, FI1.PayCodeGroupID
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID
	inner join data.ScoreFillin_PayCodeGroup FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
		and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID
where
	exists(select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID)
	and ME.IsExclusive = 1
) DUPES
	on DB.DepartmentalBudgetID = DUPES.DepartmentalBudgetID
	and DIM.PayCodeGroupID = DUPES.PayCodeGroupID
	and PH.PayCodeGroupPHID<>0

union all

--PROVIDER
-- CHECK IF PROVIDER SHOWS UP IN MORE THAN ONE SECTION
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_Provider FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join fw.DimProviderPH PH with (readuncommitted) on FI1.ProviderPHID= PH.ProviderPHID
	inner join fw.DimProvider DIM with (readuncommitted) on FI1.ProviderID = DIM.ProviderID
where exists
(select 1
from
	data.ScoreFillin_Provider FI2 with (readuncommitted)
where
	FI1.ModelGUID = FI2.ModelGUID
	and FI1.ProviderID = FI2.ProviderID
	and FI1.ProviderPHID != FI2.ProviderPHID
)
and PH.ProviderPHID<>0
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetExpenseAdjustmentsNoComments
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all non-staffing expense accounts that have manager adjustments but no comments
** Last Modified: 2017-02-27
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2017-02-27	srk		D-05574	Added isdeleted <> 1 flag, and made fiscal year parameter dynamic based on dbsetting. 
**
*************************************************************/
CREATE view [ob].[viewExceptionsDepartmentBudgetExpenseAdjustmentsNoComments] as

/******* fixed monthly adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a monthly Projection adjustment but no comments'  as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Amount<>0
and fct1.AssumptionID=38 -- Fixed Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a monthly Budget adjustment but no comments'  as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Amount<>0
and fct1.AssumptionID=38 -- Fixed Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

-- Baseline Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a Baseline Budget adjustment but no comments'  as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Amount<>0
and fct1.AssumptionID=38 -- Fixed Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=18
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

/******* Fixed Annual Adjustments ******/
-- Projected
select 	
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a yearly-level Projection adjustment but no comments'  as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted) 
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a yearly-level Budget adjustment but no comments'  as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted) 
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

/******* Subtable Adjustments ******/
-- Projected
select 	
Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a subtable Projection adjustment with no comment'  as Detail
from [clientob].[FactAccountSubtableVar] fct1 with (readuncommitted) 
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Total<>0
and fct1.AssumptionID=18
and fct1.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

-- Budget
select 	
Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a subtable Budget adjustment with no comment'  as Detail
from [clientob].[FactAccountSubtableVar] fct1 with (readuncommitted) 
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and sf.AccountPHID in ('9', --Expenses - Non-Staffing
'10') --Expenses - Zero Based
and fct1.Total<>0
and fct1.AssumptionID=18
and fct1.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetFillinCacheIssues
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match
** Last Modified: 2014-08-14
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID          Date            Author          WI      Description
** 1            2014-08-14      akk             D-02122 Filtering out not specified department budget
** 2            2016-02-26      mholov          D-03407 Filtering out 'GM Blank' model template
** 3            2016-08-10      kf              B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetFillinCacheIssues] as
--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match

--Account
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Account ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID	
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'

union all

--Job Code
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Job Code ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_JobCode FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimJobCode DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
union all

--Employee
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Employee ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Employee FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimEmployee DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
	
union all

--Pay Code Group
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Pay Code Group ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_PayCodeGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimPayCodeGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'


union all

--Provider
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Provider ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Provider FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimProvider DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
	
union all

--Charge Code
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Charge Code ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_ChargeCode FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimChargeCode DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'

union all

--OB Forecast Detail
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for OB Forecast Detail ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_OBForecastDetail FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join ob.DimOBForecastDetail DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
	
union all

--OB Departmental Budget
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for OB Departmental Budget ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_OBDepartmentalBudget FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join ob.DimDepartmentalBudget DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
	
union all

--Fiscal Year
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'

union all

--OB Financial Reporting
select
	 DB.DepartmentalBudgetID,
	 DB.Name as Model,
	 'The fill-in cache for Financial Reporting ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_OBFinancialReporting FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join ob.DimFinancialReporting DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.departmentalbudgetid<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetFillinInSubListButNotInFullList
/************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: Checks if Employee and Job Code fillins exist in Fixed or Variable sections but not the All section in the OB Departmental Budget model
** Last Modified: 2013-03-21
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
CREATE view [ob].[viewExceptionsDepartmentBudgetFillinInSubListButNotInFullList] as
--EMPLOYEE
--CHECK IF FILLINS EXISTS IN 'Staffing - Employee (Fixed)' OR  'Staffing - Employee (Variable)' BUT NOT 'Staffing - Employee (All)'
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' is in ' + PH1.Name + ' but not in Employee (All)' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_Employee FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join fw.DimEmployeePH PH1 with (readuncommitted) on FI1.EmployeePHID = PH1.EmployeePHID
	inner join fw.DimEmployee DIM with (readuncommitted) on FI1.EmployeeID = DIM.EmployeeID
where
	PH1.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)')
	and not exists
(select 1
from
	data.ScoreFillin_Employee FI2 with (readuncommitted)
	inner join fw.DimEmployeePH PH2 with (readuncommitted) on FI2.EmployeePHID = PH2.EmployeePHID
where
	PH2.Name = 'Staffing - Employee (All)'
	and FI1.ModelGUID = FI2.ModelGUID
	and FI1.EmployeeID = FI2.EmployeeID
)

union all 
--JOB CODE
-- CHECK IF FILLINS EXISTS IN 'Staffing - Job Code (Fixed)' OR  'Staffing - Job Code (Variable)' BUT NOT 'Staffing - Job Code (All)'
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	DIM.Name + ' is in ' + PH1.Name + ' but not in Job Code (All)' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join data.ScoreFillin_JobCode FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join fw.DimJobCodePH PH1 with (readuncommitted) on FI1.JobCodePHID= PH1.JobCodePHID
	inner join fw.DimJobCode DIM with (readuncommitted) on FI1.JobCodeID = DIM.JobCodeID
where
	PH1.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)')
	and not exists
(select 1
from
	data.ScoreFillin_JobCode FI2 with (readuncommitted)
	inner join fw.DimJobCodePH PH2 with (readuncommitted) on FI2.JobCodePHID = PH2.JobCodePHID
where
	PH2.Name = 'Staffing - Job Code (All)'
	and FI1.ModelGUID = FI2.ModelGUID
	and FI1.JobCodeID = FI2.JobCodeID
)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetFillinsExceedingMaxCount
/************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: Checks fillin counts > expansion count in the OB Departmental Budget model
** Last Modified: 2017-12-19
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID          Date            Author      WI          Description
** 1            2016-12-27      srk         D-04955     Provider Global ID and PH Section join updates
** 2            2017-12-19      vyaremko    D-06345     Use counts from main/base template
*************************************************************/

CREATE VIEW [ob].[viewExceptionsDepartmentBudgetFillinsExceedingMaxCount]
AS

-- ACCOUNT
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*)
            from data.ScoreFillin_Account FI with (readuncommitted)
                inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Accounts in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_Account FI with (readuncommitted) 
            inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID 
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
    ) > SE.[Count]

union all

--EMPLOYEE
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*)
            from data.ScoreFillin_Employee FI with (readuncommitted)
                inner join fw.DimEmployeePH PH with (readuncommitted) on FI.EmployeePHID = PH.EmployeePHID
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Employees in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_Employee FI with (readuncommitted) 
            inner join fw.DimEmployeePH PH with (readuncommitted) on FI.EmployeePHID = PH.EmployeePHID 
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
    ) > SE.[Count]

union all

--JOB CODE
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*)
            from data.ScoreFillin_JobCode FI with (readuncommitted)
                inner join fw.DimJobCodePH PH with (readuncommitted) on FI.JobCodePHID = PH.JobCodePHID
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Job Codes in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_JobCode FI with (readuncommitted) 
            inner join fw.DimJobCodePH PH with (readuncommitted) on FI.JobCodePHID = PH.JobCodePHID 
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
     ) > SE.[Count]

union all

--OB FINANCIAL REPORTING
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*)
            from data.ScoreFillin_OBFinancialReporting FI with (readuncommitted)
                inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI.FinancialReportingPHID = PH.FinancialReportingPHID
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Financial Reporting Lines in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_OBFinancialReporting FI with (readuncommitted) 
            inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI.FinancialReportingPHID = PH.FinancialReportingPHID 
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
    ) > SE.[Count]

union all

--PAY CODE GROUP
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*)
            from data.ScoreFillin_PayCodeGroup FI with (readuncommitted)
                inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID  and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Pay Code Groups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_PayCodeGroup FI with (readuncommitted) 
            inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID 
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
    ) > SE.[Count]

union all

--PROVIDER
select distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Has ' + cast(
        (
            select COUNT(*) 
            from data.ScoreFillin_Provider FI with (readuncommitted) 
                inner join fw.DimProviderPH PH with (readuncommitted) on FI.ProviderPHID = PH.ProviderPHID 
                inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
            where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
        ) as varchar(10))
    + ' Providers in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)
    ) as Detail
from
    XPlan X with (readuncommitted)
    inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
    inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
    left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID
    inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID)
    inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
    inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
    (
        select COUNT(*)
        from data.ScoreFillin_Provider FI with (readuncommitted)
            inner join fw.DimProviderPH PH with (readuncommitted) on FI.ProviderPHID = PH.ProviderPHID
            inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID
        where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID
    ) > SE.[Count]
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetHoursWithoutDollars
/************************************************************
** Author: akowalski
** Create Date: 2014-09-19
** Description: Checks for job code/pay code group combos that have hours but not dollars in all time periods
** Last Modified: 2017-11-15
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI			Description
** 1		10/26/2016	GF			B-13254	Refactored for performance
** 2		06/26/2017	cbb			D06077		added filter jobcodeid<>0
** 3		11/15/2017	apukii		D-06542	added filter PayCodeGroupID<>0
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetHoursWithoutDollars] 
AS
	SELECT DISTINCT
		db.DepartmentalBudgetID,
		db.Name as Model,
		'Has hours in pay code group '
			+ pcg.name
			+ ' but no dollars for job code '
			+ jc.name
			+ ' in '
			+ tc.name
			+ ' '
			+ cast(st.FiscalYearID as char(4))
			as Detail
		,tc.Name
		,st.FiscalYearID
	FROM clientob.FactStaffingPC st with (readuncommitted) 
		INNER JOIN ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=st.DepartmentalBudgetID
		INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID=st.JobCodeID
		INNER JOIN [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=st.PayCodeGroupID
		INNER JOIN [fw].[DimTimeClass] tc with (readuncommitted) on tc.TimeClassID=st.TimeClassID
	WHERE 
		st.UnitTypeID in 
			(
				51 --hours
				,146 --nonproductive
				,147 --differential
				,148 --productive
			)
		and pcg.ProductiveClassID<>4 
		and st.Total <> 0
		and jc.JobCodeID <> 0
		and pcg.PayCodeGroupID <> 0
		and not exists(
			SELECT top 1 1
			FROM clientob.FactStaffingPC d with (readuncommitted) 
			WHERE 1=1
				and d.UnitTypeID = 34
				and d.DepartmentalBudgetID=st.DepartmentalBudgetID
				and d.DataTypeID=st.DataTypeID
				and d.FiscalYearID=st.FiscalYearID
				and d.JobCodeID=st.JobCodeID
				and d.PayCodeGroupID=st.PayCodeGroupID
				and d.TimeClassID=st.timeclassID
				and d.Total != 0
		)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInactiveButYTDActivity
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all department budgets set to inactive but have YTD actuals
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetInactiveButYTDActivity] as
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is set to Inactive but has YTD account activity'  as Detail
from [clientob].[FactAccount] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID and fct1.FiscalYearID=db.BaseYear
where
db.DepartmentalBudgetID<>0 and OBActivePlans=0
and TimeClassID=1 and fct1.Total<>0
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidBenefitConfigurations
/************************************************************
** Author: mschmitz
** Create Date: 2015-01-18
** Description: Checks for budgets that have benefit accounts configured as % of Salaries or $ per FTE but do not have either Salaries or FTEs in the department
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetInvalidBenefitConfigurations] AS

SELECT DISTINCT
	FMETHOD.DepartmentalBudgetID,
	B.Name AS 'Model',
	'Has benefits budgeted as a % of Salaries but there are no benefit-driving salaries in this department.' as 'Detail'
FROM [clientob].[FactAccountVar] FMETHOD with (readuncommitted)
INNER JOIN [ob].[DimDepartmentalBudget] B ON FMETHOD.DepartmentalBudgetID=B.DepartmentalBudgetID
WHERE
	FMETHOD.AssumptionID = '220' --Forecast Method - Benefits
	AND FMETHOD.TextValue = '% of Salaries'
	--Filter to include only departments that do not have job codes filled in with benefits-driving pay code groups
	AND NOT EXISTS (
		SELECT DISTINCT
			B2.DepartmentalBudgetID
		FROM [ob].[DimDepartmentalBudget] B2 with (readuncommitted)
		INNER JOIN [dbo].[XPlan] X ON B2.MemberGUID = X.PlanGUID
		INNER JOIN [data].[ScoreFillin_PayCodeGroup] SFPCG with (readuncommitted)
			ON SFPCG.ModelGUID = B2.MemberGUID
		INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted)
			ON PCG.MemberGUID = SFPCG.FillinMemberGUID
		INNER JOIN [data].[ScoreFillin_JobCode] SFJC with (readuncommitted)
			ON SFJC.ModelGUID = B2.MemberGUID
		INNER JOIN [fw].[DimJobCode] JC with (readuncommitted)
			ON JC.MemberGUID = SFJC.FillinMemberGUID
		WHERE
			PCG.IsExcludedFromBenefits=0
			AND PCG.PayCodeGroupID<>0
			AND JC.JobCodeID<>0
			AND FMETHOD.DepartmentalBudgetID=B2.DepartmentalBudgetID
		)
		
UNION ALL

SELECT DISTINCT
	FMETHOD.DepartmentalBudgetID,
	B.Name AS 'Model',
	'Has benefits budgeted as $ per FTE but there are no benefit-driving FTEs in this department.' as 'Detail'
FROM [clientob].[FactAccountVar] FMETHOD with (readuncommitted)
INNER JOIN [ob].[DimDepartmentalBudget] B ON FMETHOD.DepartmentalBudgetID=B.DepartmentalBudgetID
WHERE
	FMETHOD.AssumptionID = '220' --Forecast Method - Benefits
	AND FMETHOD.TextValue = '$ per FTE'
	--Filter to include only departments that do not have job codes filled in with benefits-driving pay code groups
	AND NOT EXISTS (
		SELECT DISTINCT
			B2.DepartmentalBudgetID
		FROM [ob].[DimDepartmentalBudget] B2 with (readuncommitted)
		INNER JOIN [dbo].[XPlan] X ON B2.MemberGUID = X.PlanGUID
		INNER JOIN [data].[ScoreFillin_PayCodeGroup] SFPCG with (readuncommitted)
			ON SFPCG.ModelGUID = B2.MemberGUID
		INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted)
			ON PCG.MemberGUID = SFPCG.FillinMemberGUID
		INNER JOIN [data].[ScoreFillin_JobCode] SFJC with (readuncommitted)
			ON SFJC.ModelGUID = B2.MemberGUID
		INNER JOIN [fw].[DimJobCode] JC with (readuncommitted)
			ON JC.MemberGUID = SFJC.FillinMemberGUID
		WHERE
			PCG.IsExcludedFromBenefits=0
			AND PCG.PayCodeGroupID<>0
			AND JC.JobCodeID<>0
			AND FMETHOD.DepartmentalBudgetID=B2.DepartmentalBudgetID
		)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidDeductionSetups
/*********************************************************************************************************************************
** Author: mschmitz
** Create Date: 2015-01-19
** Description: Checks for budgets that have contract labor dollars budgeted without hours
** Last Modified: 2016-11-30
** GM Release: 2015.2
**********************************************************************************************************************************
** Change History
**********************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		2016-11-30	srk		D-04897		Updated view to include only 'Deductions' placeholder section and 
**											ignore 'Deductions - Reimbursement' section because this section does not 
**											require gross charges in the same department. Deductions in the Reimbursement section 
**											are pushed from the Reimbursement model.
**
*********************************************************************************************************************************/

CREATE VIEW [ob].[viewExceptionsDepartmentBudgetInvalidDeductionSetups] AS

select distinct
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is set to drive deductions by '+ ac.Textvalue+ ' but has no gross charge accounts in the model' as Detail
from [data].[ScoreFillin_Account] sf1 with (readuncommitted)
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID
	inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID
	inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID and a.OBModelSectionName = 'Deductions'
	inner join [clientob].[FactAccountVar] ac with (readuncommitted) on sf1.AccountID=ac.AccountID and ac.DepartmentalBudgetID=db.DepartmentalBudgetID
where 1=1
	and ph1.Name = 'Deductions'
	and (ac.TextValue like '%charges' or ac.TextValue = 'Default')
	and ac.AssumptionID=631 --'Deductions as a percent of'
	and ac.TimeClassID=12
	and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists (
		select top 1 1
		from [data].[ScoreFillin_Account] SF with (readuncommitted)
		inner join [ob].[DimAccountPH] ph with (readuncommitted)
			on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
			and ph.Name like 'Gross Charges%'
		where
			db.MemberGUID=SF.ModelGUID
			and SF.AccountID<>0
		)
	and db.DepartmentalBudgetID<>0


Union all

-- check for accounts using default on Global Methods tab
/*********  Assumptions
1. Deductions are only ever filled in to the section that matches the patient class set on account in order to pull the global setting
2. Doesn't check if you have gross charges for the specific patient class selected
3. Doesn't check payor specific
*************/

select distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is globally set to drive deductions by '+ fct2.Textvalue+ ' but has no gross charge accounts in the model' as Detail
from [data].[ScoreFillin_Account] sf1 with (readuncommitted)
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID
	inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID
	inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID and a.OBModelSectionName = 'Deductions'
	inner join [clientob].[FactAccountVar] fct1 with (readuncommitted) on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID  and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID
		and fct1.AssumptionID=fct2.AssumptionID
where 1=1
	and ph1.Name = 'Deductions'
	and fct1.AssumptionID=631 --Volume Driver
	and fct1.TextValue='Global Default'
	and fct1.TimeClassID=12
	and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and (fct2.TextValue like '%charges' or fct2.TextValue = 'Default')
	and not exists (
		select top 1 1
		from [data].[ScoreFillin_Account] SF with (readuncommitted)
		inner join [ob].[DimAccountPH] ph with (readuncommitted)
			on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
			and ph.Name like 'Gross Charges%'
		where db.MemberGUID=SF.ModelGUID
			and SF.AccountID<>0
		)
	and db.DepartmentalBudgetID<>0
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidDropdownSelection
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2016-12-05
** GM Release: 2014.3
*********************************************************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2015-06-15	BL					Filter out Not Specified Members (false positives)
** 2		2016-12-05	SK		D-04790	When there are no different pay code groups, 
												false positives need to be filtered for the differential 
												hours and wage rates methodologies
*********************************************************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidDropdownSelection] as
--Accounts
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Account ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from clientob.factaccountvar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID
where fct.UnitTypeID=141 
--CID 1 --
and DIM.AccountID<>0
and TextValue_Formula='x'
and TextValue=''

Union all

-- Job Codes
select distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Job Code ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from clientob.FactStaffingPCVar fct with (readuncommitted)
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID
	inner join [fw].[DimPayCodeGroup] pcg on fct.PayCodeGroupID = pcg.PayCodeGroupID
	INNER JOIN [fw].[DimAssumption] DA on fct.AssumptionID = DA.AssumptionID
where fct.UnitTypeID=141
--CID 1 --
	and DIM.JobCodeID<>0
	and TextValue_Formula='x'
	and TextValue=''
	and EmployeeID=0
-- CID 2 --
	and not
		(
			(select count(1) from [fw].[DimPayCodeGroup] pcg1 where PCG1.ProductiveClassID = 5) = 0
			and DA.Name in ('Differential Hours Methodology', 'Differential Rate Methodology')
		)
-- CID 2 --

Union all

-- Providers
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Provider ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from clientob.FactProviderVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID
where fct.UnitTypeID=141 
--CID 1 --
and DIM.ProviderID<>0
and TextValue_Formula='x'
and TextValue=''

union all
-- Employees
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Employee ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from clientob.FactStaffingPCVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimEmployee DIM with (readuncommitted) on fct.EmployeeID = DIM.EmployeeID
where fct.UnitTypeID=141 
--CID 1 --
and DIM.EmployeeID<>0
and TextValue_Formula='x'
and TextValue=''
and DIM.EmployeeID<>0

union all
-- Global Methods
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Global Method ' + Dim.LineName + ' has an invalid drop-down box selection'  as Detail
from clientob.FactAccountRollupVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join ob.DimFinancialReporting DIM with (readuncommitted) on fct.FinancialReportingID=DIM.FinancialReportingID
where fct.UnitTypeID=141 
--CID 1 --
and DIM.FinancialReportingID<>0
and TextValue_Formula='x'
and TextValue=''
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidGrossChargesSetups
CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidGrossChargesSetups] as
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Find mismatches between how the gross charge accounts are setup and what information is available in the model
** Last Modified: 2016-11-30
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2015-01-19	akk	D-02448		Updating charge code section to look at global methods tab in addition to account level
** 2		2016-11-23	cbb	D-03536		Provider - remove false positives when global methods are set to provider allocation
** 3		2016-11-30	srk	D-04844		Updated first two unions to flag exceptions that don't have a primary revenue driver in the primary stat config screen
*************************************************************/

SELECT DISTINCT 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is set to drive charges by  '+ ac.Textvalue+ ' but has no statistics in the model' as Detail
from clientob.FactAccountVar ac with (readuncommitted)
	inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID
where 1=1
	and ac.TextValue like '%UOS%'
	and ass.Name='Volume Driver'
	and ac.TimeClassID = 12
	and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from data.ScoreFillin_Account SF with (readuncommitted)
	inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
		and (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
	INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
		AND PSC.AccountID = SF.AccountID
	where db.MemberGUID=SF.ModelGUID
		and SF.AccountID<>0
		AND PSC.Revenue = 1
	)
	and db.DepartmentalBudgetID<>0
	
Union all

-- check for accounts using default on Global Methods tab
/*********  Assumptions
1. Gross Charges are only ever filled in to the section that matches the patient class set on account in order to pull the global setting
2. Doesn't check if you have stats for the specific patient class selected
3. Doesn't check payor specific
*************/

SELECT
	DISTINCT  
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is set to drive charges by  '+ fct2.Textvalue+ ' but has no statistics in the model' as Detail
from [data].[ScoreFillin_Account] sf1 with (readuncommitted)
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID
	inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID
	inner join clientob.FactAccountVar fct1 with (readuncommitted)  on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID
	inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID
		and fct1.AssumptionID=fct2.AssumptionID
	inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct2.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5'
where 1=1
	and ph1.Name like 'Gross Charge%'
	and fct1.AssumptionID=184 --Volume Driver
	and fct1.TextValue='Global Default'
	and fct2.TextValue like '%UOS%'
	and fct1.TimeClassID = 12
	and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from data.ScoreFillin_Account SF with (readuncommitted)
	inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
		and (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
	INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
		AND PSC.AccountID = SF.AccountID
	where 1=1
		and db.MemberGUID=SF.ModelGUID
		and SF.AccountID<>0
		and PSC.Revenue = 1
	)
	and db.DepartmentalBudgetID<>0



union all


SELECT
	DISTINCT  
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is set to drive charges by  '+ ac.Textvalue+ ' but has no charge codes in the model' as Detail
from clientob.FactAccountVar ac with (readuncommitted)
	inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID
where 1=1
	and TextValue like '%CDM%'
	and ass.Name='Volume Driver'
	and ac.TimeClassID = 12
	and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from data.ScoreFillin_ChargeCode SF with (readuncommitted)
	inner join fw.DimChargeCodePH PH with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
	where 1=1
		and db.MemberGUID=SF.ModelGUID
		and sf.ChargeCodeID<>0
	)
	and db.DepartmentalBudgetID<>0

Union all

SELECT
	DISTINCT  
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is set to drive charges by  '+ ac.Textvalue+ ' but has no providers in the model' as Detail
from clientob.FactAccountVar ac with (readuncommitted)
	inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID
where 1=1
	and TextValue like '%Provider%'
	and ass.Name='Volume Driver'
	and ac.TimeClassID = 12
	and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from data.ScoreFillin_Provider SF with (readuncommitted)
	inner join fw.DimProviderPH PH with (readuncommitted)	on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
	where 1=1
	and db.MemberGUID=SF.ModelGUID
	and sf.ProviderID<>0
	)
	and db.DepartmentalBudgetID<>0

union all

--===============  BEGIN CID 1 ========================
SELECT
	DISTINCT  
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Is calculating revenue by charge code in section ' + substring(ph.Name,16,100) + ' but has no gross charge accounts configured to be impacted' as Detail
from data.ScoreFillin_ChargeCode SF with (readuncommitted)
	inner join [fw].[DimChargeCodePH] ph with (readuncommitted) on SF.ChargeCodePHID=ph.ChargeCodePHID
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) 
		on SF.ModelGUID=db.MemberGUID
		and not exists 
		(
			select top 1 1 
			from clientob.FactAccountVar fct1 with (readuncommitted)
				inner join [fw].[DimAccount] a on fct1.AccountID=a.AccountID and a.PatientClass=substring(ph.Name,16,100)
			where 1=1
				and db.MemberGUID=SF.ModelGUID
				and DB.DepartmentalBudgetID=fct1.DepartmentalBudgetID
				and TextValue like '%CDM%'
				and fct1.AssumptionID=184 --Volume Driver
				and fct1.TimeClassID = 12
				and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
		)
		and not exists 
		(
			select top 1 1 
			from clientob.FactAccountRollupVar fct1 with (readuncommitted)
				inner join [fw].[DimPatientClass] pc on fct1.patientclassid=pc.PatientClassID and pc.Name=substring(ph.Name,16,100)
				inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct1.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5'
				inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct2.DepartmentalBudgetID=fct1.DepartmentalBudgetID and fct1.AssumptionID=fct2.AssumptionID
				inner join [fw].[DimAccount] a on fct2.AccountID=a.AccountID and pc.PatientClassID=a.PatientClassID
				inner join [data].[ScoreFillin_Account] sf on a.AccountID=sf.AccountID and DB.MemberGUID=sf.ModelGUID
			where 1=1
				and db.MemberGUID = SF.ModelGUID
				and DB.DepartmentalBudgetID = fct1.DepartmentalBudgetID
				and fct1.TextValue like '%CDM%'
				and fct1.AssumptionID = 184 --Volume Driver
				and fct2.TextValue = 'Global Default'
				and fct1.TimeClassID = 12
				and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
				and sf.AccountPHID in 
				(
					'468', --'Gross Charges - Clinic',
					'467', --'Gross Charges - ED',
					'14', --'Gross Charges - Inpatient',
					'466', --'Gross Charges - Observation',
					'16', --'Gross Charges - Other',
					'18'--'Gross Charges - Outpatient'
				)
		)
		and sf.ChargeCodeID<>0
		and db.DepartmentalBudgetID<>0

--===============  END CID 1 ========================

union all

--===============  BEGIN CID 2 ========================
SELECT
	DISTINCT  
	DepartmentalBudgetID	= dB.DepartmentalBudgetID,
	Model					= dB.Name,
	Detail					= 'Is calculating revenue by provider but has no gross charge accounts configured to be impacted'
from data.ScoreFillin_Provider SF with (readuncommitted)
	inner join [fw].[DimProviderPH] ph on SF.PlaceholderSectionMemberGUID = ph.MemberGUID
	inner join ob.DimDepartmentalBudget DB with (readuncommitted) 
		on SF.ModelGUID=db.MemberGUID
		and not exists 
		(
			select top 1 1 
			from clientob.FactAccountVar AC with (readuncommitted)
				inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID
			where 1=1
				and DB.DepartmentalBudgetID = AC.DepartmentalBudgetID
				and ac.TextValue = 'Provider Charge Allocation'
				and ass.Name = 'Volume Driver'
				and ac.TimeClassID = 12
				and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
		)
		and not exists
		(
			select top 1 1 
			from clientob.FactAccountRollupVar fct1 with (readuncommitted)
				inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct2.DepartmentalBudgetID=fct1.DepartmentalBudgetID and fct1.AssumptionID=fct2.AssumptionID
				inner join [fw].[DimAccount] a with (readuncommitted) on fct2.AccountID=a.AccountID and fct1.PatientClassID=a.PatientClassID
				inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on a.AccountID=sf.AccountID and DB.MemberGUID=sf.ModelGUID
			where 1=1
				and db.MemberGUID=SF.ModelGUID
				and DB.DepartmentalBudgetID=fct1.DepartmentalBudgetID
				and fct1.TextValue = 'Provider Charge Allocation'
				and fct1.AssumptionID = 184 --Volume Driver
				and fct2.TextValue = 'Global Default'
				and fct1.TimeClassID = 12
				and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
				and sf.AccountPHID in 
				(
					'468', --'Gross Charges - Clinic',
					'467', --'Gross Charges - ED',
					'14', --'Gross Charges - Inpatient',
					'466', --'Gross Charges - Observation',
					'16', --'Gross Charges - Other',
					'18'--'Gross Charges - Outpatient'
				)
		)
		and sf.ProviderID<>0
		and db.DepartmentalBudgetID<>0

--===============  END CID 2 ========================
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidSpreadSelections
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays any spread methods that will not match anything on the spreads tab
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetInvalidSpreadSelections] as
-- account
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has an invalid spread setting for account ' + sf.FillinMemberName + 'in section ' + ph.Name as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2
and fct1.TextValue not in (
	-- hard coded spreads
	select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',')

	union all

	-- global spreads
	select fct1.Name from [clientob].[FactGlobalSpreads] fct1
	inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0

	union all

	-- department specific spreads
	select Text from [clientob].[FactSpreadVar] fct2
	where fct2.AssumptionID=117 --Spread Name
	and fct2.DepartmentalBudgetID<>0
	and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID
)

union all

-- Job Code dollars only
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has an invalid spread setting for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.AssumptionID=116 --Spread Method
and fct1.PayCodeGroupID<>0
and fct1.TimeClassID=2
and fct1.TextValue not in (
	-- hard coded spreads
	select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',')

	union all

	-- global spreads
	select fct1.Name from [clientob].[FactGlobalSpreads] fct1
	inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0

	union all

	-- department specific spreads
	select Text from [clientob].[FactSpreadVar] fct2
	where fct2.AssumptionID=117 --Spread Name
	and fct2.DepartmentalBudgetID<>0
	and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID
)

union all

-- charge code volume spread
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has an invalid volume spread setting for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2
and fct1.TextValue not in (
	-- hard coded spreads
	select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',')

	union all

	-- global spreads
	select fct1.Name from [clientob].[FactGlobalSpreads] fct1
	inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0

	union all

	-- department specific spreads
	select Text from [clientob].[FactSpreadVar] fct2
	where fct2.AssumptionID=117 --Spread Name
	and fct2.DepartmentalBudgetID<>0
	and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID
)

union all

/************* Provider overrides ********************/

-- Budget vol/rev
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has an invalid spread setting for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2
and fct1.TextValue not in (
	-- hard coded spreads
	select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',')

	union all

	-- global spreads
	select fct1.Name from [clientob].[FactGlobalSpreads] fct1
	inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0

	union all

	-- department specific spreads
	select Text from [clientob].[FactSpreadVar] fct2
	where fct2.AssumptionID=117 --Spread Name
	and fct2.DepartmentalBudgetID<>0
	and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID
)

union all

-- Budget comp
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has an invalid spread setting for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.AssumptionID=107 --Projection Method
and fct1.TimeClassID=2
and fct1.TextValue not in (
	-- hard coded spreads
	select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',')

	union all

	-- global spreads
	select fct1.Name from [clientob].[FactGlobalSpreads] fct1
	inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0

	union all

	-- department specific spreads
	select Text from [clientob].[FactSpreadVar] fct2
	where fct2.AssumptionID=117 --Spread Name
	and fct2.DepartmentalBudgetID<>0
	and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID
)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetInvalidVariableExpenseConfigurations
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Finds departments with variable job codes or accounts with no statistics configured to drive them
** Last Modified: 2017-02-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID	Date		Author			WI			Description
** 1	2016-11-29	srk			D-04844			In templates >2016.3, stat driver assumptions are not stored in var tables. 
**												these need to be pulled directly from the primary statistic table.
** 2	2016-02-27	srk			D-05529			Fixed join on department ID. 	
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidVariableExpenseConfigurations] as

--INVALID STAFFING DRIVER CONFIGURATION

SELECT 
DISTINCT 
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Has variable job codes but no statistic accounts configured as staffing drivers' as Detail
FROM [data].[ScoreFillin_JobCode] SF1 with (readuncommitted)
	INNER JOIN ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF1.ModelGUID
	INNER JOIN [fw].[DimDepartment] DD with (readuncommitted) on DB.DepartmentID=DD.DepartmentID
WHERE 
	1=1
	AND	SF1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable)
	AND DD.IsVariable=1
	AND NOT EXISTS 
		(
		SELECT top 1 1 from data.ScoreFillin_Account SF with (readuncommitted)
		INNER JOIN ob.DimAccountPH PH with (readuncommitted) on PH.MemberGUID=sf.PlaceholderSectionMemberGUID
			AND (ph.Name  like 'Statistics%' OR ph.Name like 'Global Stat%')
		INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
			AND PSC.AccountID = SF.AccountID
		WHERE DB.MemberGUID=SF.ModelGUID
			AND SF.AccountID<>0
			AND PSC.Staffing = 1 --Staffing Driver
		)
	
union all

--INVALID NON-STAFFING EXPENSE DRIVER CONFIGURATION


SELECT 
DISTINCT 
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Has variable expense accounts but no statistic accounts configured as expense account drivers' as Detail
FROM [data].[ScoreFillin_Account] SF1 with (readuncommitted)
	INNER JOIN ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF1.ModelGUID
	INNER JOIN [fw].[DimDepartment] DD with (readuncommitted) on DB.DepartmentID=DD.DepartmentID  --CID 2
	INNER JOIN [fw].[DimAccount] DA on SF1.AccountID=DA.AccountID
WHERE 
	1=1 
	AND	SF1.PlaceholderSectionMemberGUID='aa2a181f-d126-4b47-ac88-dba1445508a7' --Expenses - Non-Staffing
	AND DD.IsVariable=1
	AND DA.Variability=1
	AND NOT EXISTS 
		(
		SELECT top 1 1 from data.ScoreFillin_Account SF with (readuncommitted)
		INNER JOIN ob.DimAccountPH PH with (readuncommitted) on PH.MemberGUID=SF.PlaceholderSectionMemberGUID
		AND (PH.Name  like 'Statistics%' or PH.Name like 'Global Stat%')
		INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
			AND PSC.AccountID = SF.AccountID
		WHERE db.MemberGUID=SF.ModelGUID
			AND SF.AccountID<>0
			AND PSC.NonStaffingExpense = 1 --Non-Staffing Expense Driver
		)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingGlobalStatisticConfigurations
/************************************************************
** Author: akowalski
** Create Date: 2014-09-19
** Description: Checks statistics filled into department budgets where there is a global statistic model associated with the department
** Last Modified: 2014-09-19
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view ob.viewExceptionsDepartmentBudgetMissingGlobalStatisticConfigurations as
select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears as a statistic in the model but has no global statistic configured' as Detail
from data.ScoreFillin_Account SF with (readuncommitted) 
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID
inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID
inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=d.DepartmentID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and gs.Name is null
and db.DepartmentalBudgetID<>0
and d.OBGlobalStatisticsPlanID<>0
and a.IsGlobal=0

union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears as a statistic in the department model but is not filled into the global statistic model' as Detail
from data.ScoreFillin_Account SF with (readuncommitted) 
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID
inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID
inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=d.DepartmentID
inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
left outer join [data].[ScoreFillin_OBGlobalStatistics] sf2 with (readuncommitted) on sf2.ModelGUID=gsp.MemberGUID and sf2.FillinMemberGUID=gs.MemberGUID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and sf2.FillinGUID is null
and db.DepartmentalBudgetID<>0
and d.OBGlobalStatisticsPlanID<>0
and a.IsGlobal=0


union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears as a statistic in the department model but is not configured in the global stats to department mapping table' as Detail
from data.ScoreFillin_Account SF with (readuncommitted) 
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID
inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID
inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=0
left outer join [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted) on fct.OBGlobalStatisticsPlanID=gsp.OBGlobalStatisticsPlanID and d.DepartmentID=fct.DepartmentID and fct.OBGlobalStatisticID=gs.OBGlobalStatisticID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and fct.RowID is null
and db.DepartmentalBudgetID<>0
and d.OBGlobalStatisticsPlanID<>0
and a.IsGlobal=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingNotSpecifiedFillins
/************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: Finds all missing not specified fillins in the OB Departmental Budget model for the Account, Employee, Job Code, OB Financial Reporting, Pay Code Group, and Provider dimensions
** Last Modified: 2013-03-21
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetMissingNotSpecifiedFillins] as
select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Is Missing the Not Specified Employee' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
where
	not exists(select 1 from data.ScoreFillin_Employee FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.EmployeeID = 0 and FI.EmployeePHID = 0)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1

union all

select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Is Missing the Not Specified Job Code' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
where
	not exists(select 1 from data.ScoreFillin_JobCode FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.JobCodeID = 0 and FI.JobCodePHID = 0)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1

union all

select
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Is Missing the Not Specified Pay Code Group' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
where
	not exists(select 1 from data.ScoreFillin_PayCodeGroup FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayCodeGroupID = 0 and FI.PayCodeGroupPHID = 0)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingPayrollToAccountCrosswalkConfigurations
/************************************************************
** Author: mschmitz
** Create Date: 2015-01-18
** Description: Checks for job code/pay code group combos that have dollars budgeted but no matching GL account in the payroll to account crosswalk
** Last Modified: 2016-11-25
** GM Release: 2017.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-11-25  vyaremko        D-04954
**
*************************************************************/
CREATE VIEW ob.viewExceptionsDepartmentBudgetMissingPayrollToAccountCrosswalkConfigurations AS
SELECT DISTINCT
	F.DepartmentalBudgetID,
	B.Name AS 'Model',
	CASE F.UnitTypeID 
		WHEN 34	THEN 'Has ' + PCG.Name +' dollars budgeted to ' + JC.Name + ' but this payroll combination is not mapped to a GL account'
		WHEN 51 THEN 'Has ' + PCG.Name +' hours budgeted to ' + JC.Name + ' but this payroll combination is not mapped to a GL account'
	END AS 'Detail'
FROM [clientob].[FactStaffingPC] F with (readuncommitted)
INNER JOIN [ob].[DimDepartmentalBudget] B with (readuncommitted)
	ON F.DepartmentalBudgetID = B.DepartmentalBudgetID
INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted)
	ON F.PayCodeGroupID = PCG.PayCodeGroupID
INNER JOIN [fw].[DimJobCode] JC with (readuncommitted)
	ON F.JobCodeID = JC.JobCodeID
WHERE
		F.Total <> 0
	AND F.UnitTypeID in (34, 51)
	AND F.DataTypeID = 3
	AND NOT EXISTS (
		SELECT 1
		FROM [clientob].[FactPayrollToAccountCrosswalk] X with (readuncommitted)
		WHERE				
			(
				(X.JobCodeID = F.JobCodeID AND X.PayCodeGroupID = F.PayCodeGroupID) --pay code group and job code specific
				OR (X.JobCodeID = F.JobCodeID AND X.PayCodeGroupID = 0)				--job code specific
				OR (X.JobCodeID = 0 AND X.PayCodeGroupID = F.PayCodeGroupID)		--pay code group specific
			)
		AND X.UnitTypeID = F.UnitTypeID
		AND X.IsDeleted = 0
	)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingPrimaryStatisticConfigurations
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Find mismatches between what is configured in the department primary statistic table and what is actually filled into the model
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-12-1	blewis	D-02439	Report should exclude inactive departments and fixed departments without gross charges
**
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetMissingPrimaryStatisticConfigurations] as

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears as a statistic in the model but is not configured in the driver statistic table' as Detail
from data.ScoreFillin_Account SF with (readuncommitted) 
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID
--*********************CID 1 *******************************
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID
--*********************CID 1 *******************************
inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID
inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
left outer join [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) on DB.DepartmentID=ps.DepartmentID and a.AccountID=ps.AccountID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and ps.RowID is null
and db.DepartmentalBudgetID<>0
--*********************CID 1 *******************************
and d.IsVariable=1
and d.IsActive=1
--*********************CID 1 *******************************

union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears in the driver statistic table but does not appear in the model' as Detail
from [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ps.DepartmentID=db.DepartmentID
--*********************CID 1 *******************************
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID
--*********************CID 1 *******************************
inner join [fw].[DimAccount] a with (readuncommitted) on ps.AccountID=a.AccountID
cross join [ob].[DimAccountPH] ph with (readuncommitted)
left outer join data.ScoreFillin_Account SF with (readuncommitted) on a.AccountID=SF.AccountID and DB.MemberGUID=SF.ModelGUID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and sf.RowID is null
and db.DepartmentalBudgetID<>0
--*********************CID 1 *******************************
and d.IsVariable=1
and d.IsActive=1
--*********************CID 1 *******************************

--Fixed Departments with Charges (Section Unioned for CID 1)

union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears as a statistic in the model but is not configured in the driver statistic table' as Detail
from data.ScoreFillin_Account SF with (readuncommitted) 
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID
inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID
inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
left outer join [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) on DB.DepartmentID=ps.DepartmentID and a.AccountID=ps.AccountID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and ps.RowID is null
and db.DepartmentalBudgetID<>0
and d.IsVariable=0
and d.IsActive=1
--Only Include Fixed Departments with Charges
and DB.MemberGUID IN(SELECT sfa.[ModelGUID]
					FROM [data].[ScoreFillin_Account] sfa
					inner join [ob].[DimAccountPH] aph on sfa.AccountPHID=aph.AccountPHID
					where aph.Name like 'Gross Charges%')

union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	a.Name + ' appears in the driver statistic table but does not appear in the model' as Detail
from [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ps.DepartmentID=db.DepartmentID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID
inner join [fw].[DimAccount] a with (readuncommitted) on ps.AccountID=a.AccountID
cross join [ob].[DimAccountPH] ph with (readuncommitted)
left outer join data.ScoreFillin_Account SF with (readuncommitted) on a.AccountID=SF.AccountID and DB.MemberGUID=SF.ModelGUID
where (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
and sf.RowID is null
and db.DepartmentalBudgetID<>0
and d.IsVariable=0
and d.IsActive=1
--Only Include Fixed Departments with Charges
and DB.MemberGUID IN(SELECT sfa.[ModelGUID]
					FROM [data].[ScoreFillin_Account] sfa
					inner join [ob].[DimAccountPH] aph on sfa.AccountPHID=aph.AccountPHID
					where aph.Name like 'Gross Charges%')
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingProductivityStandards
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Finds departments with variable job codes but no productivity standard specified
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date			Author				WI			Description
** 1		2016-02-01	CBB/BL(assist)	D-03585	exclude plans if template setting is projected
**
*************************************************************/

create view [ob].[viewExceptionsDepartmentBudgetMissingProductivityStandards] as
select 
Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Has variable job codes but no productivity standard specified for the current year projection' as Detail
from [data].[ScoreFillin_JobCode] sf1 with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=sf1.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID
--CID 1 begin
inner join [dbo].[XPlan] x on DB.MemberGUID=x.PlanGUID
inner join [dbo].[TemplateSettings] ts on x.ModelTemplateGUID=ts.TemplateGUID
--CID 1 end
where sf1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable)
and d.IsVariable=1 and db.OBActivePlans=1
and (db.WorkedHrsperUOSProjection=0)
--CID 1 begin
and ts.SettingID='GlobalDefaults_Staffing_HrsperUOS_ProjectedOrSupplied'
and ts.Value='Supplied'
--CID 1 end

union all
	
select 
Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Has variable job codes but no productivity standard specified for next year''s budget' as Detail
from [data].[ScoreFillin_JobCode] sf1 with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=sf1.ModelGUID
inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID
--CID 1 begin
inner join [dbo].[XPlan] x on DB.MemberGUID=x.PlanGUID
inner join [dbo].[TemplateSettings] ts on x.ModelTemplateGUID=ts.TemplateGUID
--CID 1 end
where sf1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable)
and d.IsVariable=1 and DB.OBActivePlans=1
and (db.WorkedHrsperUOSBudget=0)
--CID 1 begin
and ts.SettingID='GlobalDefaults_Staffing_HrsperUOS_ProjectedOrSupplied'
and ts.Value='Supplied'
--CID 1 end
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingProviderBenefitAccounts
CREATE view [ob].[viewExceptionsDepartmentBudgetMissingProviderBenefitAccounts]
 as
select
    distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Is forecasting provider benefit type ' + fd.Name + ' but has no benefit accounts filled into the model' as Detail
from
    ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join [data].[ScoreFillin_OBForecastDetail] sf on db.memberguid=sf.ModelGUID and OBForecastDetailPHID=18 --Provider - Benefits
	inner join [ob].[DimOBForecastDetail] fd on sf.OBForecastDetailID=fd.OBForecastDetailID
    inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
where
    not exists (select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID<>0 and FI.AccountPHID = 7 /*Benefits*/)
    and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingProviderDeductionAccounts
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Budgets that are forecasting deductions by provider, but do not have the associated deductions accounts filled-in to the model.
** Last Modified:
** GM Release: 2015.2
*************************************************************/
Create view [ob].[viewExceptionsDepartmentBudgetMissingProviderDeductionAccounts]
 as
select
    distinct
    DB.DepartmentalBudgetID,
    DB.Name as Model,
    'Is forecasting provider deduction type ' + fd.Name + ' but has no deduction accounts filled into the model' as Detail
from
    ob.DimDepartmentalBudget DB with (readuncommitted)
	inner join [data].[ScoreFillin_OBForecastDetail] sf on db.memberguid=sf.ModelGUID and OBForecastDetailPHID=5 --Provider - Deductions
	inner join [ob].[DimOBForecastDetail] fd on sf.OBForecastDetailID=fd.OBForecastDetailID
    inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
where
    not exists (select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID<>0 and FI.AccountPHID = 4 /*Deductions*/)
    and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingSelfFillin
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Displays any department budgets that are missing their self fill-in
** Last Modified: 2014-05-13
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetMissingSelfFillin] as

select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Department Budget ' + db.Name + ' is missing the self-fill-in'  as Detail
from ob.DimDepartmentalBudget DB with (readuncommitted)
left outer join data.ScoreFillin_OBDepartmentalBudget sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='58106837-6396-47A4-9876-05DD97C9224E'
where sf.FillinGUID is null
and db.DepartmentalBudgetID<>0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetMissingXPlanRecords
/************************************************************
** Author: akowalski
** Create Date: 2014-09-22
** Description: Checks for poorly created plans (plans with a dimension record but no xplan record)
** Last Modified: 2014-09-22
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view ob.viewExceptionsDepartmentBudgetMissingXPlanRecords as
select 
Distinct
db.DepartmentalBudgetID,
d.Name as Model,
'Department Budget record exists in the ob.dimdepartmentalbudget table but not in xplan' as Detail
from [ob].[DimDepartmentalBudget] db
left outer join [fw].[DimDepartment] d on db.DepartmentID=d.DepartmentID
left outer join [dbo].[XPlan] xp on DB.MemberGUID=xp.PlanGUID
where xp.Name is null
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetModelToReconciliationTargetComparision
CREATE view [ob].[viewExceptionsDepartmentBudgetModelToReconciliationTargetComparision] as
/************************************************************
** Author: akowalski
** Create Date: 2014-06-12
** Description: Compares the post-model refresh financial statement results with the target financial statement values specified using the reconciliation tool
** Last Modified: 2014-06-12
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI			Description
** 1		2016-12-14	srk			D-04952	Case statement for detail description	
*************************************************************/
select 
	0 as DepartmentalBudgetID,
	'Not Specified' as Model,
	fr.Name + ' has value ' + cast(round(src.Amount,0) as varchar(25)) + ' for Entity: ' + 
	e.Name + ' but should have ' + cast(round(trgt.Amount,0) as varchar(25)) + 
	' in ' + tc.Name + ' ' + cast(src.fiscalyearid as varchar(4)) + 
	case when src.fiscalmonthid = 0 then '' else ' in Month ' + m.name END as Detail
from [ob].[viewFactReportingMonthlyTargetComparision] src
inner join [ob].[ReconciliationTarget] trgt 
	on trgt.EntityID=src.EntityID
	and trgt.FiscalYearID=src.FiscalYearID
	and trgt.TimeClassID=src.TimeClassID
	and trgt.FinancialReportingID=src.FinancialReportingID
	and trgt.FiscalMonthID=src.FiscalMonthID
inner join [ob].[DimFinancialReporting] fr on src.FinancialReportingID=fr.FinancialReportingID
inner join [fw].[DimEntity] e on src.EntityID=e.EntityID
inner join [fw].[DimTimeClass] tc on src.TimeClassID=tc.TimeClassID
inner join [fw].[DimFiscalMonth] m on src.FiscalMonthID=m.FiscalMonthID
where round(trgt.Amount,-2)<>round(src.Amount,-2)
and round(trgt.Amount,-1)<>round(src.Amount,-1)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetNoReviewerAssignments
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all non-staffing expense accounts that have manager adjustments but no comments
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetNoReviewerAssignments] as
select 	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Has no reviewers configured'  as Detail from [ob].[DimDepartmentalBudget] db
inner join [dbo].[XPlan] xp on db.MemberGUID=xp.PlanGUID
where xp.PlanTypeGUID='05512126-3eb6-4da4-af6e-bc2bc2724b8b'
and db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and not exists(select 1 from [dbo].[viewS3RoleAssignmentDetail] ra 
where lootGroupID like 'DEPT|%' and ra.RoleName like 'OB - %' and xp.CachedLootID=ra.LootID
)
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetOrphanedData
/*************************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Checks for nonzero data that will not show up in the model because a fillin is missing
** Last Modified: 2014-05-13
** GM Release: 2014.3
***************************************************************************
** Change History
***************************************************************************
** CID		Date		Author	WI		Description
** 1		2016-12-27	srk		D-05208	Filtering out inactive providers
** 2		2016-12-29	srk		D-05186	Filtering out prior year budget timeclass
**************************************************************************/


CREATE view [ob].[viewExceptionsDepartmentBudgetOrphanedData] as

-- Account data
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data in Account ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		clientob.FactAccount data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimAccount dim with (readuncommitted) on dim.AccountID = data.AccountID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'77A0029B-F072-4ED6-8BFC-89BCFD6ED049' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2
		and db.DepartmentalBudgetID<>0
		and dim.AccountID<>0
		and not (dim.OBIsDefined=1 and dim.OBAccountPHID=0 and dim.OBStatModelSectionID=0)
		and db.obactiveplans=1
		
UNION ALL

--Job Code Data
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data in Job Code ' + dim.Name+ ' but it is not filled in' as Detail
	
	from 
		clientob.FactStaffingPC data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimJobCode dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'26FE98B4-987C-403B-84E3-6630F96001F9' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2
		and db.DepartmentalBudgetID<>0
		and dim.JobCodeID<>0
		and db.obactiveplans=1
		
UNION ALL

--Pay Code Group
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data in Pay Code Group ' + dim.Name+ ' but it is not filled in' as Detail
	
	from 
		clientob.FactStaffingPC data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimPayCodeGroup dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'119D96CF-81AF-4D69-A671-5E5B23F9F9DD' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2
		and db.DepartmentalBudgetID<>0
		and dim.PayCodeGroupID<>0
		and db.obactiveplans=1

UNION ALL

--Employee
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data for Employee ' + dim.Name+ ' but it is not filled in' as Detail
	
	from 
		clientob.FactStaffingPC data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimEmployee dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'A3882825-3889-4669-BA58-886F984F739F' --not specified
		inner join DBSetting s with (readuncommitted) on s.Name='OB_Employee_Detail' and s.Setting='1'
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2	
		and db.DepartmentalBudgetID<>0
		and dim.EmployeeID<>0
		and db.obactiveplans=1
		

UNION ALL

--Provider Data
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data for Provider ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		clientob.FactProvider data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimProvider dim with (readuncommitted) on dim.ProviderID = data.ProviderID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2	
		and db.DepartmentalBudgetID<>0
		and dim.ProviderID<>0
		-- CID 1
		and dim.OBIsActive = 1
		-- CID 1
	 	and db.obactiveplans=1
		
UNION ALL

--Charge Code Data
	select
	Distinct
	db.DepartmentalBudgetID,
	db.Name as Model,
	'Has data for Charge Code ' + dim.Name+ ' but it is not filled in' as Detail
	
	from 
		clientob.FactCDM data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join fw.DimChargeCode dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'9482496E-5ABF-452A-884D-BF874AABF0DC' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and
		--CID 2
		(((
		data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data
		and data.timeclassid = 1
		)
		or
		(
		data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year
		and data.timeclassid = 2
		)
		or
		(
		data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year
		and data.timeclassid = 2
		)))
		--CID 2	
		and db.DepartmentalBudgetID<>0
		and dim.ChargeCodeID<>0
	 	and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetOverriddenCalculations
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all instances of the use of the override option
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetOverriddenCalculations] as
/************* Account overrides ********************/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.TimeClassID=2

union all
/************* Job Code overrides ********************/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue like '%Override%'
and fct1.UnitTypeID=141
and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed)
'52') --Staffing - Job Code (Variable)
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue like '%Override%'
and fct1.UnitTypeID=141
and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed)
'52') --Staffing - Job Code (Variable)
and fct1.TimeClassID=2

union all

-- Baseline Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue like '%Override%'
and fct1.UnitTypeID=141
and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed)
'52') --Staffing - Job Code (Variable)
and fct1.TimeClassID=18

union all

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and sf2.PayCodeGroupID<>0
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and sf2.PayCodeGroupID<>0
and fct1.TimeClassID=2

union all
/************* Employee overrides ********************/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.EmployeeID<>0
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.EmployeeID<>0
and fct1.TimeClassID=2

union all

/************* Charge Code overrides ********************/

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.TimeClassID=2

union all
/************* Provider overrides ********************/

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Projection calculations for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the Budget calculations for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.TextValue='Override'
and fct1.UnitTypeID=141
and fct1.TimeClassID=2
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetOverrideProjectionOrSpread
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all instances of overriding the default projection or spread methods
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetOverrideProjectionOrSpread] as
/************* Account overrides ********************/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=107 --Projection Method
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default spread method for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2

union all
-- Contract Labor Dollars
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Account ' + sf.FillinMemberName + ' in section Contract Labor Dollars' as Detail
from [clientob].[FactAccountVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=625 --Dollars Method
and sf.AccountPHID=6 --Staffing - Contract Labor
and fct1.TimeClassID=12


union all
/************* Job Code overrides ********************/
-- Fixed projection
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and fct1.JobCodeID<>0
and fct1.AssumptionID=116 --Spread Method (template is mapped wrong)
and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed)
'52') --Staffing - Job Code (Variable)
and fct1.TimeClassID=12

union all

-- variable projection
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and fct1.JobCodeID<>0
and fct1.AssumptionID=81 --Non-Productive FTE Adjustment (template is mapped wrong)
and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed)
'52') --Staffing - Job Code (Variable)
and fct1.TimeClassID=12

union all

-- hr/uos projection
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Hrs per UOS Target' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [fw].[DimAssumption] ass  with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and ass.Name='Productive Hrs per UOS Projection Method'
and fct1.TimeClassID=12

union all

--  hr/uos spread
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default budget method for Hrs per UOS Target' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [fw].[DimAssumption] ass  with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and ass.Name='Productive Hrs per UOS Projection Method'
and fct1.TimeClassID=2

union all

-- skill mix projection
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Skill Mix' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [fw].[DimAssumption] ass  with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and ass.Name='Skill Mix Projection Method'
and fct1.TimeClassID=12

union all

--  skill mix spread
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default budget method for Skill Mix' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [fw].[DimAssumption] ass  with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.EmployeeID=0
and fct1.PayCodeGroupID=0
and ass.Name='Skill Mix Projection Method'
and fct1.TimeClassID=2


union all

-- Projected hrs distribution
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the Hours Distribution calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=627 --Hours Method
and sf2.PayCodeGroupID<>0
and fct1.TimeClassID=1

union all

-- Projected wage rate
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the Wage Rate calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=625 --Dollars Method
and sf2.PayCodeGroupID<>0
and fct1.TimeClassID=1

union all

-- Projected dollars only
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=107 --Projection Method
and fct1.PayCodeGroupID<>0
and fct1.TimeClassID=12

union all

-- Budget dollars only
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default spread method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=116 --Spread Method
and fct1.PayCodeGroupID<>0
and fct1.TimeClassID=2

union all
/************* Employee overrides ********************/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is overriding the default projection method for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.TextValue<>'Default'
and fct1.AssumptionID=116 --Spread Method (this is wrong in the template)
and fct1.JobCodeID=0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID<>0
and fct1.TimeClassID=12


union all

/************* Charge Code overrides ********************/

-- Projected volume
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the volume projection method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.TextValue<>'Default'
and fct1.AssumptionID=634 --Rate Projection Method (this is wrong in the template)
and fct1.TimeClassID=12

union all

-- Projected rate
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the rate projection method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.TextValue<>'Default'
and fct1.AssumptionID=632 --Volume Projection Method (this is wrong in the template)
and fct1.TimeClassID=12

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the volume spread method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail
from [clientob].[FactCDMVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID
inner join [fw].[DimPatientClass] pc  with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ChargeCodeID<>0
and fct1.TextValue<>'Default'
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2

union all
/************* Provider overrides ********************/

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the default projection method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.TextValue_Formula='x'
and fct1.AssumptionID=107 --Projection Method
and fct1.TimeClassID=12

union all

-- Budget vol/rev
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the default spread method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.TextValue_Formula='x'
and fct1.AssumptionID=116 --Spread Method
and fct1.TimeClassID=2

union all

-- Budget comp
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Is Overriding the default spread method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail
from [clientob].[FactProviderVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID
inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1
and fct1.ProviderID<>0
and fct1.TextValue_Formula='x'
and fct1.AssumptionID=107 --Projection Method
and fct1.TimeClassID=2
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetPlansNotInWorkflow
/************************************************************
** Author: jgerber
** Create Date: 2014-10-07
** Description: Finds all departmental budgets without workflows
** Last Modified: 2014-11-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-10-07	JG				Renaming and adding to the exception summary report 
** 2		2014-11-18	cbecker	D-02416	Filtering out not specified departmental budget 
**
*************************************************************/
CREATE view [ob].[viewExceptionsDepartmentBudgetPlansNotInWorkflow]
as
	select 
		ob.DepartmentalBudgetID,
		ob.Name as Model,
		'Has a departmental budget but does not have an associated workflow.' as Detail
	from 
		ob.viewDimDepartmentalBudget OB
	where
		not exists(
			select 
				1 
			from 
				ob.viewDimDepartmentalBudget P
				inner join WFToken T on T.EntityGUID = P.MemberGUID
				inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID
			where 
				WF.Name like 'OB%'
				and P.MemberGUID = OB.MemberGUID
		)
		and OB.DepartmentalBudgetID<>0
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetPotentiallyInvalidGrossChargesSetups
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Find mismatches between how the gross charge accounts are setup and what information is available in the model but may produce some false positives
** Last Modified: 2016-11-30
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI		Description
** 1		2016-11-30		srk		D-04844		Updated first two unions to flag exceptions that don't have a primary revenue driver in the primary stat config screen 
**
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetPotentiallyInvalidGrossChargesSetups] as

select
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Has ' + a.PatientClass + ' Gross Charges and is set to drive charges by '+ ac.Textvalue+ ' but has no ' + a.PatientClass + ' statistics in the model' as Detail
from [clientob].[FactAccountVar] ac with (readuncommitted)
	inner join [fw].[DimAssumption] ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID
	inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimAccount] a with (readuncommitted) on ac.AccountID=a.AccountID
where 1=1
	and TextValue like '%UOS%'
	and ass.Name='Volume Driver'
	and ac.TimeClassID = 12
	and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from [data].[ScoreFillin_Account] SF with (readuncommitted)
	inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
		and (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
	inner join [fw].[DimAccount] a2 on SF.AccountID=a2.AccountID
	INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
		AND PSC.AccountID = SF.AccountID
	where 1=1
		and db.MemberGUID=SF.ModelGUID
		and SF.AccountID<>0
		and a.PatientClassID=a2.PatientClassID
		and PSC.Revenue = 1
	)
	and db.DepartmentalBudgetID<>0
	
Union all

select 
	Distinct 
	dB.DepartmentalBudgetID,
	dB.Name as Model,
	'Has ' + a.PatientClass + ' Gross Charges and is set to drive charges by '+ fct2.Textvalue+ ' but has no ' + a.PatientClass + ' statistics in the model' as Detail
from [data].[ScoreFillin_Account] sf1 with (readuncommitted)
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID
	inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID
	inner join [clientob].[FactAccountVar] fct1 with (readuncommitted)  on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID
	inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID
		and fct1.AssumptionID=fct2.AssumptionID
	inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct2.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5'
where 1=1
	and ph1.Name like 'Gross Charge%'
	and fct1.AssumptionID=184 --Volume Driver
	and fct1.TextValue='Global Default'
	and fct2.TextValue like '%UOS%'
	and fct1.TimeClassID = 12
	and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year')
	and not exists 
	(
	select top 1 1 from [data].[ScoreFillin_Account] SF with (readuncommitted)
	inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID
		and (ph.Name  like 'Statistics%' or ph.Name like 'Global Stat%')
	inner join [fw].[DimAccount] a2 on SF.AccountID=a2.AccountID
	INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID
	where 1=1
		and db.MemberGUID=SF.ModelGUID
		and SF.AccountID<>0
		and a.PatientClassID=a2.PatientClassID
		and PSC.Revenue = 1
	)
	and db.DepartmentalBudgetID<>0
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProjectedBudgetVarianceTooHigh
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays financial statement lines who have a greater than 50% change from projection to budget time
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create view [ob].[viewExceptionsDepartmentBudgetProjectedBudgetVarianceTooHigh] as
select 
	DB.DepartmentalBudgetID,
	dB.Name as Model,
	'Has Projected to Budgeted Variance of '+ cast(100*(Sum(Budgeted)- SUM(Projected))/SUM(Projected) as nvarchar)+'% in '+ DIM.Name as Detail
 from (select 
		FR.DepartmentalBudgetID,
		FR.FinancialReportingID,
		case when TimeClassID=2 and FiscalYearID= (select s.Setting +1  from [dbo].[DBSetting] s where Name = 'OB_Current_Year') then Total else 0 END As Budgeted,
		case when TimeClassID=12 and FiscalYearID= (select s.Setting   from [dbo].[DBSetting] s where Name = 'OB_Current_Year') then Total else 0 END As Projected 
	from clientob.FactReportingMonthly FR with (readuncommitted)
	where TimeClassID in (2,12)) as Agg
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on AGG.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join ob.DimFinancialReporting DIM with (readuncommitted) on DIM.financialreportingID=AGG.FinancialReportingID
where dim.Statement='IS'
group by DB.DepartmentalBudgetID,
dB.Name ,
dim.Name
having SUM(projected)<>0
and case when SUM(projected)<>0 then abs((Sum(Budgeted)- SUM(Projected))/SUM(Projected)) end > 0.5
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProjectedEqualYTD
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Compares Projected total and YTD to determine of the anything is being projected in the non-closed months, indicates potential errors
** Last Modified: 2014-05-13
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetProjectedEqualYTD] as


-- Account Data
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Has projected = YTD for Account: ' + Dim.Name + ' in section ' + PH.Name  as Detail
from clientob.FactAccount fct with (readuncommitted)
inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID
inner join  data.ScoreFillin_Account SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	and dim.MemberGUID=sf.FillinMemberGUID
inner join ob.DimAccountPH PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.MonthsLoaded<>12

union all


-- Staffing Data
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Has projected dollars = YTD for Pay Code Group "' + pcg.Name + '" of Job Code ' + dim.Name  as Detail
from clientob.FactStaffingPC fct with (readuncommitted)
inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID
inner join fw.DimPayCodeGroup pcg with (readuncommitted) on fct.PayCodeGroupID=pcg.PayCodeGroupID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.UnitTypeID=34
and fct.MonthsLoaded<>12

union all

-- Provider Data
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Has projected = YTD for forecast detail "' + fd.Name + '" of Provider ' + dim.Name  as Detail
from clientob.FactProvider fct with (readuncommitted)
inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID
inner join ob.DimOBForecastDetail fd with (readuncommitted) on fct.OBForecastDetailID=fd.OBForecastDetailID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.MonthsLoaded<>12

union all


-- Charge Code Data
select 
Distinct
DB.DepartmentalBudgetID,
DB.Name as Model,
'Has projected dollars = YTD for charge code ' + dim.Name   as Detail
from clientob.FactCDM fct with (readuncommitted)
inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
inner join fw.DimChargeCode DIM with (readuncommitted) on fct.ChargeCodeID = DIM.ChargeCodeID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.UnitTypeID=34
and fct.MonthsLoaded<>12
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderCompToAccount
/***********************************************************************************************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: If forecast detail category starts with provider compensation, needs to have account fillin to Staffing GL Accounts section
** Last Modified: 2017-03-22
** GM Release: 2014.4
*************************************************************************************************************************************************
** Change History
*************************************************************************************************************************************************
** CID		Date		Author	WI		Description
** 1		2014-09-04	akk		D-02183	Removing false positives for unmapped items and budgets with no providers
** 2		2017-01-11	srk		D-05145	Updated second part of the script (after the first union) to check for mid-levels only
										because it is looking for secondary accounts on the forecast dimension. Also included a check 
										for Staffing - Hours Accounts.
** 3		2017-03-22	srk		D-05711	Removed 'Provider - Benefits' from this exception view because it only needs to look for comp exceptions									
************************************************************************************************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetProviderCompToAccount] as
select
	distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Account ' + A.Name + ' is configured to receive Physician data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join ob.DimOBForecastDetail OBFD with (readuncommitted)
	inner join fw.DimAccount A with (readuncommitted) on OBFD.AccountID = A.AccountID
	inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - GL Accounts' -- Physician Account
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid
--CID 2 BEGIN--
	inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type = 'Physician' 
--CID 2 END--
where 1=1
	and OBFD.Category in ('Provider Compensation - Production Earning Tiers','Provider Compensation - Other Pay','Provider Compensation - Guarantee') -- Only Dollars
	and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
	and A.AccountID<>0
	
UNION ALL

select
	distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Account ' + A.Name + ' is configured to receive Mid-Level Physician data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join ob.DimOBForecastDetail OBFD with (readuncommitted)
	inner join fw.DimAccount A with (readuncommitted) on OBFD.SecondaryAccountID = A.AccountID -- Mid-Level Account
	inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - GL Accounts'
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid
--CID 2 BEGIN--
	inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type <> 'Physician'
--CID 2 END--
where 1=1
	and OBFD.Category in ('Provider Compensation - Production Earning Tiers','Provider Compensation - Other Pay','Provider Compensation - Guarantee') -- Only Dollars
	and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
	and A.AccountID<>0


--CID 2 BEGIN -- INCLUDING HOURS ACCOUNTS--
UNION ALL

select
	distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Account ' + A.Name + ' is configured to receive Physician hours data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join ob.DimOBForecastDetail OBFD with (readuncommitted)
	inner join fw.DimAccount A with (readuncommitted) on OBFD.AccountID = A.AccountID
	inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - Hours Accounts' -- Physician Account
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid
--CID 2 BEGIN--
	inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type = 'Physician' 
--CID 2 END--
where 1=1
	and OBFD.Category in ('Provider Compensation - Hours') -- Only Hours
	and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
	and A.AccountID<>0
	
UNION ALL

select
	distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Account ' + A.Name + ' is configured to receive Mid-Level Physician hours data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join ob.DimOBForecastDetail OBFD with (readuncommitted)
	inner join fw.DimAccount A with (readuncommitted) on OBFD.SecondaryAccountID = A.AccountID -- Mid-Level Account
	inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - Hours Accounts'
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid
--CID 2 BEGIN--
	inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type <> 'Physician'
--CID 2 END--
where 1=1
	and OBFD.Category in ('Provider Compensation - Hours') -- Only Hours
	and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID)
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
	and A.AccountID<>0
	
--CID 2 END -- INCLUDING HOURS ACCOUNTS--
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderDeductionsMissingRevenue
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Budgets that have providers with data in a driven volume but no data in the driver volume.  This causes the driven volume to not project or budget.
** Last Modified:
** GM Release: 2015.2
*************************************************************/
Create view [ob].[viewExceptionsDepartmentBudgetProviderDeductionsMissingRevenue]
 as

	select distinct 
	db.departmentalbudgetid,
	db.name As Model,
	'Provider' + prov.Name + ' has deductions but no revenue' As Detail
	from [ob].[DimDepartmentalBudget] DB 
	inner join [data].[ScoreFillin_OBForecastDetail] fd  on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=5
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
	inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid
	inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID in (47,50)
	inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID 
	where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderDrivenVolumesMissingDriver
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Budgets that have providers with data in a driven volume but no data in the driver volume.  This causes the driven volume to not project or budget.
** Last Modified:
** GM Release: 2015.2
*************************************************************/
Create view [ob].[viewExceptionsDepartmentBudgetProviderDrivenVolumesMissingDriver]
 as
	select distinct 
	db.departmentalbudgetid,
	db.name As Model,
	'Provider' + prov.Name + ' has driven but no volume' As Detail
	from [ob].[DimDepartmentalBudget] DB 
	inner join [data].[ScoreFillin_OBForecastDetail] fd  on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=3
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
	inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid
	inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID <> 0
	inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID 
	where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderFTEGreaterThan1
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Providers whose total FTE across all departments is greater than 1.  This usually indicates an oversubscription of a provider to one or more departments.
** Last Modified:
** GM Release: 2015.2
*************************************************************
** Change History
**************************************************************
** CID          Date            Author      WI          Description
** 1            2018-01-02      sdominsk   D-06353     Added additional grouping on year/timeclass and use the working hours table to convert FTEs to hours, total them, then convert total back to FTEs.
*************************************************************/
CREATE view [ob].[viewExceptionsDepartmentBudgetProviderFTEGreaterThan1]
 as
select
	Distinct
	DB.DepartmentalBudgetID,
	DB.Name as Model,
	'Provider ' + prov.Name + ' has ' + Cast(TotalFTE as varchar(100)) + ' which is greater than 1 for all departments' As Detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join ob.DimOBForecastDetail OBFD with (readuncommitted)
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid
	inner join ( select fte.FiscalYearID,
                        TimeClassID,
                        ProviderID,
                        SUM(fte.Month01*WorkH.Month01+fte.Month02*workH.Month02+fte.Month03*workH.Month03+fte.Month04*workH.Month04+fte.Month05*workH.Month05+fte.Month06*workH.Month06+fte.Month07*workH.Month07+fte.Month08*workH.Month08+fte.Month09*workH.Month09+fte.Month10*workH.Month10+fte.Month11*workH.Month11+fte.Month12*workH.Month12)
                        /SUM(WorkH.Month01+workH.Month02+workH.Month03+workH.Month04+workH.Month05+workH.Month06+workH.Month07+workH.Month08+workH.Month09+workH.Month10+workH.Month11+workH.Month12)
                       as TotalFTE
                    from [clientob].[FactProvider] fte
                            inner join ob.DimDepartmentalBudget as DBi with (readuncommitted) on dbi.DepartmentalBudgetID = fte.DepartmentalBudgetID
                            inner join fw.DimEntity as DEi with (readuncommitted) on DBi.EntityID = DEi.EntityID
                            inner join [client].[FactWorkingHoursPerMonth]  WorkH on WorkH.FiscalYearID = fte.FiscalYearID and WorkH.WorkWeekID = DEi.WorkWeekID
					where 
                        OBForecastDetailID=1001
                    group by
                        Providerid,fte.FiscalYearID,TimeClassID
                ) rollup on sfp.ProviderID=rollup.ProviderID 
    inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.ProviderID 
where
    DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
    and TotalFTE  > 1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderProductionEarningsMissingDriver
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Budgets that have providers with data in a driven volume but no data in the driver volume.  This causes the driven volume to not project or budget.
** Last Modified:
** GM Release: 2015.2
*************************************************************/
Create view [ob].[viewExceptionsDepartmentBudgetProviderProductionEarningsMissingDriver]
 as
	select distinct 
	db.departmentalbudgetid,
	db.name As Model,
	'Provider' + prov.Name + ' has productive earnings tiers but no volumes' As Detail
	from [ob].[DimDepartmentalBudget] DB 
	inner join [data].[ScoreFillin_OBForecastDetail] fd  on fd.OBForecastDetailID=fd.OBForecastDetailID
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
	inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid
	inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID and fp.TimeClassID in (2,12)
	where prov.OBTier1Threshold <> 0 and fp.Total =0
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
	UNION 
	select distinct 
	db.departmentalbudgetid,
	db.name As Model,
	'Provider' + prov.Name + ' has productive earnings tiers but no volumes' As Detail
	from [ob].[DimDepartmentalBudget] DB 
	inner join [data].[ScoreFillin_OBForecastDetail] fd  on fd.OBForecastDetailID=fd.OBForecastDetailID
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
	inner join ob.DimobForecastDetail ob on ob.OBForecastDetailID=fd.OBForecastDetailID and OB.IsSalaryDriver=1
	inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid 
	inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID and fp.TimeClassID in (2,12)
	where prov.OBTier1Threshold <> 0 and fp.Total =0
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetProviderRevenueMissingDriverVolume
/************************************************************
** Author: bparrott
** Create Date: 2015-01-18
** Description: Budgets that have providers with data in a driven volume but no data in the driver volume.  This causes the driven volume to not project or budget.
** Last Modified:
** GM Release: 2015.2
*************************************************************/
Create view [ob].[viewExceptionsDepartmentBudgetProviderRevenueMissingDriverVolume]
 as
	select distinct 
	db.departmentalbudgetid,
	db.name As Model,
	'Provider' + prov.Name + ' has revenue but no volumes' As Detail
	from [ob].[DimDepartmentalBudget] DB 
	inner join [data].[ScoreFillin_OBForecastDetail] fd  on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=4
	inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0
	inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid
	inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID in (47,50)
	inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID 
	where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4
	and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetRegularPCGNoHoursNoDollars
/************************************************************
** Author: mschmitz
** Create Date: 2015-01-18
** Description: Checks for budgets that have zero YTD 'Regular' hours/dollars but have non-zero values in other pay code groups which depend on the Regular type having non-zero values
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetRegularPCGNoHoursNoDollars] AS

SELECT DISTINCT
	B.DepartmentalBudgetID,
	B.Name as 'Model',
	'Has non-regular YTD hours/dollars for job code '+JC.name+' but no regular YTD hours/dollars for this job code.  The model will be unable to project the non-regular dollars.' as 'Detail'
FROM ( --Non-zero OTHER YTD dollars
       SELECT top (2147483647)
              OTH.DepartmentalBudgetID,
              OTH.JobCodeID,
              OTH.PayCodeGroupID,
			  OTH.UnitTypeID
       FROM [clientob].[FactStaffingPC] OTH with (readuncommitted)
       WHERE
              OTH.UnitTypeID in ('34','51','146','147','148')
              AND OTH.DataTypeID=4
              AND OTH.TimeClassID=1
              AND OTH.FiscalYearID IN (SELECT Setting from [dbo].[DBSetting] with (readuncommitted) WHERE Name like 'OB_Current_Year')
              AND OTH.PayCodeGroupID NOT IN (SELECT PCGD.PayCodeGroupID FROM [fw].[DimPayCodeGroup] PCGD with (readuncommitted) WHERE PCGD.ProductiveClassID = 4) --Exclude Dollars Only
              AND OTH.PayCodeGroupID NOT IN (--Exludes the first Productive pay code group member
                     SELECT DISTINCT SFOTH.PayCodeGroupID FROM [data].[ScoreFillin_PayCodeGroup] SFOTH with (readuncommitted)
                     WHERE
                           SFOTH.PlaceholderSectionMemberGUID = 'c0294680-5658-454f-90fd-7bfc686131aa'
                           AND SFOTH.PlaceholderIndex=0
                     )
              AND OTH.YTD<>0
       GROUP BY
              OTH.DepartmentalBudgetID,
              OTH.JobCodeID,
              OTH.PayCodeGroupID,
			  OTH.UnitTypeID
       HAVING SUM(OTH.YTD)<>0
       ) OTHER
INNER JOIN ( --Zero REGULAR YTD dollars
       SELECT top (2147483647)
              REG.DepartmentalBudgetID,
              REG.JobCodeID,
			  REG.UnitTypeID
       FROM [clientob].[FactStaffingPC] REG with (readuncommitted)
       WHERE
              REG.UnitTypeID in ('34','51','146','147','148')
              AND REG.DataTypeID=4
              AND REG.TimeClassID=1
              AND REG.FiscalYearID IN (SELECT Setting from [dbo].[DBSetting] with (readuncommitted) WHERE Name like 'OB_Current_Year')
              AND REG.PayCodeGroupID IN (--Includes the first Productive pay code group member
                     SELECT DISTINCT SFREG.PayCodeGroupID FROM [data].[ScoreFillin_PayCodeGroup] SFREG with (readuncommitted)
                     WHERE
                           SFREG.PlaceholderSectionMemberGUID = 'c0294680-5658-454f-90fd-7bfc686131aa' 
                           AND SFREG.PlaceholderIndex=0
                     )
       GROUP BY
              REG.DepartmentalBudgetID,
              REG.JobCodeID,
			  REG.UnitTypeID
       HAVING SUM(REG.YTD)=0
       ) REGULAR
       ON OTHER.DepartmentalBudgetID=REGULAR.DepartmentalBudgetID
		AND OTHER.JobCodeID=REGULAR.JobCodeID
		AND OTHER.UnitTypeID=REGULAR.UnitTypeID
INNER JOIN [ob].[DimDepartmentalBudget] B with (readuncommitted)
       ON REGULAR.DepartmentalBudgetID = B.DepartmentalBudgetID
INNER JOIN [fw].[DimJobCode] JC with (readuncommitted)
       ON REGULAR.JobCodeID=JC.JobCodeID
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetStaffingAdjustmentsNoComments
/************************************************************
** Author: akowalski
** Create Date: 2015-01-18
** Description: Displays all job codes that have manager adjustments but no comments
** Last Modified: 2017-02-27
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2017-02-27	srk		D-05574	Adding isdeleted filter and making fiscal year parameter dynamic
**
*************************************************************/
CREATE view [ob].[viewExceptionsDepartmentBudgetStaffingAdjustmentsNoComments] as

/**********************************************************************************
**************   Fixed Job Code Adjustments ***************************************
**********************************************************************************/
/******* Monthly FTE adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

/******* Annual FTE Adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a yearly-level FTE Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a yearly-level FTE Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1



union all

/******* Non-productive % ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

-- Baseline Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Baseline Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=2 --Staffing - Job Code (Fixed)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=18
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

/**********************************************************************************
**************   Employee Adjustments ***************************************
**********************************************************************************/
/******* Monthly FTE adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Employee ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.EmployeePHID=202 --Staffing - Employee (Fixed)
and fct1.JobCodeID=0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID<>0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Employee ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.EmployeePHID=202 --Staffing - Employee (Fixed)
and fct1.JobCodeID=0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID<>0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

/******* Annual FTE Adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Employee ' + sf.FillinMemberName + ' has a yearly-level FTE Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.EmployeePHID=202 --Staffing - Employee (Fixed)
and fct1.JobCodeID=0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID<>0
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Employee ' + sf.FillinMemberName + ' has a yearly-level FTE Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.EmployeePHID=202 --Staffing - Employee (Fixed)
and fct1.JobCodeID=0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID<>0
and fct1.Amount<>0
and fct1.AssumptionID=18 -- Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1

union all

/**********************************************************************************
**************   Variable Job Code Adjustments ***************************************
**********************************************************************************/
/******* Monthly FTE adjustments ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Variable Job Code ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=52 --Staffing - Job Code (Variable)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Variable Job Code ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=52 --Staffing - Job Code (Variable)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=620 -- Productive Adjustment
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

/******* Non-productive % ******/
-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Projection adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=52 --Staffing - Job Code (Variable)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=12
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Projected
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=52 --Staffing - Job Code (Variable)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=2
and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1


union all

-- Baseline Budget
select 
	Distinct
	db.DepartmentalBudgetID as DepartmentalBudgetID,
	db.Name as Model,
	'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Baseline Budget adjustment but no comments'  as Detail
from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted)
inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID
inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID
where
db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 
and sf.JobCodePHID=52 --Staffing - Job Code (Variable)
and fct1.JobCodeID<>0
and fct1.PayCodeGroupID=0
and fct1.EmployeeID=0
and fct1.Amount<>0
and fct1.AssumptionID=155 -- Non-Productive Mix
and fct2.AssumptionID=30 -- Comment
and fct2.Comment=''
and fct1.TimeClassID=18
and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year')
and fct1.IsDeleted <> 1
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetUnfilledInPayrollAccounts
/************************************************************
** Author: dmoldawer
** Create Date: 2014-03-21
** Description: Checks payroll accounts crosswalk for unfilled-in accounts
** Last Modified: 2017-02-10
** GM Release: 2017.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2017-02-10	akk		D-05027	Adding hours to view and making it work with all crosswalk types
**
*************************************************************/

CREATE view [ob].[viewExceptionsDepartmentBudgetUnfilledInPayrollAccounts] as

---- Exceptions for Dollars Option 3b (and the overrides of 3a)
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive salary data from Pay Code Group ' + DPG.Name + ' and Job Code ' 
	+ DJC.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID 
	inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all)
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - GL Accounts'
)
and CW.PayCodeGroupID<>0
and CW.JobCodeID<>0
and CW.UnitTypeID=34 --dollars

union all

---- Exceptions for Dollars Option 2
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive salary data from Job Code ' 
	+ DJC.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all)
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - GL Accounts'
)
and CW.PayCodeGroupID=0
and CW.JobCodeID<>0
and CW.UnitTypeID=34 --dollars

union all

---- Exceptions for Dollars Option 1 and the defaults for 3a
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive salary data from Pay Code Group ' + DPG.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID 
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - GL Accounts'
)
and exists (select 1 from [data].[ScoreFillin_JobCode] FI with (readuncommitted) 
		where FI.ModelGUID = DB.MemberGUID
		and FI.PlaceholderSectionMemberGUID='e9ce521d-6953-4636-94cd-b36798515385' -- Job Code (All)
		and FI.JobCodeID<>0
		)
and CW.PayCodeGroupID<>0
and CW.JobCodeID=0
and CW.UnitTypeID=34 --dollars

union all

---- Exceptions for Hours Option 3b (and the overrides of 3a)
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive hours data from Pay Code Group ' + DPG.Name + ' and Job Code ' 
	+ DJC.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID 
	inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all)
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - Hours Accounts'
)
and CW.PayCodeGroupID<>0
and CW.JobCodeID<>0
and CW.UnitTypeID=51 -- hours

union all

---- Exceptions for Hours Option 2
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive hours data from Job Code ' 
	+ DJC.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all)
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - Hours Accounts'
)
and CW.PayCodeGroupID=0
and CW.JobCodeID<>0
and CW.UnitTypeID=51 -- hours

union all

---- Exceptions for Hours Option 1 and the defaults for 3a
select
	DB.DepartmentalBudgetID,
	db.name as Model,
	'Account ' + DA.Name + ' is configured to receive hours data from Pay Code Group ' + DPG.Name + ' but is not filled in to the department' as detail
from
	ob.DimDepartmentalBudget DB with (readuncommitted)
	cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted)
	inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID
	inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID
	inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID
	inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID 
where db.obactiveplans=1
	and not exists
(select
	1
from
	data.ScoreFillin_Account FI with (readuncommitted)
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID
where
	FI.ModelGUID = DB.MemberGUID
	and PH.Name = 'Staffing - Hours Accounts'
)
and exists (select 1 from [data].[ScoreFillin_JobCode] FI with (readuncommitted) 
		where FI.ModelGUID = DB.MemberGUID
		and FI.PlaceholderSectionMemberGUID='e9ce521d-6953-4636-94cd-b36798515385' -- Job Code (All)
		and FI.JobCodeID<>0
		)
and CW.PayCodeGroupID<>0
and CW.JobCodeID=0
and CW.UnitTypeID=51 -- hours
GO


---------------------------------------------

-- ob.viewExceptionsDepartmentBudgetUnmappedProviderForecastItems
/************************************************************
** Author: akowalski
** Create Date: 2014-05-13
** Description: Displays any provider comp forecast details that are not mapped to an account (which will prevent them from impacting the income statement)
** Last Modified: 2014-05-13
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		7/8/16     vyaremko B-11627 Adding filter for 'Hours' and 'FTEs'
** 2		8/1/16     vyaremko B-11627 Exclude 'FTEs' from exception report
**
*************************************************************/
CREATE VIEW [ob].[viewExceptionsDepartmentBudgetUnmappedProviderForecastItems] AS

SELECT
	DISTINCT
	db.[DepartmentalBudgetID],
	db.[Name] AS Model,
	'Forecast detail ' + fd.[Name] + ' does not have an GL account associated with it for Physician Providers' as Detail
FROM [ob].[DimDepartmentalBudget] AS db WITH (READUNCOMMITTED)
	INNER JOIN [data].[ScoreFillin_Provider] AS sf  WITH (READUNCOMMITTED) ON db.[MemberGUID] = sf.[ModelGUID] AND 
		sf.[PlaceholderSectionMemberGUID] <> '93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified
	CROSS JOIN [ob].[DimOBForecastDetail] AS fd WITH (READUNCOMMITTED)
WHERE 
		(fd.[Category] LIKE 'Provider Comp%')
	AND ((fd.[AccountID] = 0) OR (fd.[Account] = '0 - Not Specified'))
	AND 
	(
			((fd.[Category] <> 'Provider Compensation - FTEs') AND (fd.[Category] <> 'Provider Compensation - Hours'))
		OR ((fd.[Category] = 'Provider Compensation - Hours') AND EXISTS(SELECT 1 FROM [dbo].[SystemCenterStep] AS scs WHERE scs.[GlobalID] = 'HourstoAccountMappings' AND (CAST(scs.[PropertyXML].query('//IsHoursChecked/text()') AS NVARCHAR(5)) = 'True')))
	)
	AND (db.[DepartmentalBudgetID] <> 0)

UNION ALL

SELECT
	DISTINCT
	db.[DepartmentalBudgetID],
	db.[Name] as Model,
	'Forecast detail ' + fd.[Name] + ' does not have an GL account associated with it for Non-Physician Providers' AS Detail
FROM [ob].[DimDepartmentalBudget] AS db WITH (READUNCOMMITTED)
	INNER JOIN [data].[ScoreFillin_Provider] AS sf WITH (READUNCOMMITTED) ON db.[MemberGUID] = sf.[ModelGUID] AND 
		sf.[PlaceholderSectionMemberGUID] <> '93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified
	CROSS JOIN [ob].[DimOBForecastDetail] AS fd WITH (READUNCOMMITTED)
WHERE 
		(fd.[Category] LIKE 'Provider Comp%')
	AND ((fd.[SecondaryAccountID] = 0) OR (fd.[SecondaryAccount] = '0 - Not Specified'))
	AND 
	(
			((fd.[Category] <> 'Provider Compensation - FTEs') AND (fd.[Category] <> 'Provider Compensation - Hours'))
		OR ((fd.[Category] = 'Provider Compensation - Hours') AND EXISTS(SELECT 1 FROM [dbo].[SystemCenterStep] AS scs WHERE scs.[GlobalID] = 'HourstoAccountMappings' AND (CAST(scs.[PropertyXML].query('//IsHoursChecked/text()') AS NVARCHAR(5)) = 'True')))
	)
	AND (db.[DepartmentalBudgetID] <> 0)
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsAccountsNotBudgeted
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Finds any accounts that have YTD data but don't have a budget
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsAccountsNotBudgeted]
as

select 
	db.OBGlobalStatisticsPlanID, 
	db.Name as Model, 
	'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Global Statistic '+acc.Name+' but does not have a budget' as Detail

from [clientob].[FactGlobalStatistics] fa
inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID
inner join [ob].[DimOBGlobalStatistics] acc on acc.OBGlobalStatisticID=fa.OBGlobalStatisticID
inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID
where 
	FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
	and TimeClassID=1
	and Total<>0
	and acc.OBGlobalStatisticID<>0
	and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor)
	and not exists 
		(select 
			1 
		from 
			[clientob].[FactGlobalStatistics] fa2
		where 
			FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
			and TimeClassID=2 
			and Total<>0 
			and fa2.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID 
			and fa2.OBGlobalStatisticID=fa.OBGlobalStatisticID
			and fa2.UnitTypeID=fa.UnitTypeID)
group by
	db.OBGlobalStatisticsPlanID, 
	db.Name,
	ut.Name,
	acc.Name
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsAllocationsNot100Pct
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Checks for any reportable global stat being allocated any differently than 100%
** Last Modified: 08/22/2017
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID      Date        Author      WI      Description
** 1        08/22/2017  vyaremko    05689   Ignore deleted records
**
*************************************************************/

CREATE VIEW [ob].[viewExceptionsGlobalStatsAllocationsNot100Pct] 
AS

SELECT
    DISTINCT
    GSP.[OBGlobalStatisticsPlanID] AS [OBGlobalStatisticsPlanID],
    GSP.[Name] AS [Model],
    'Has an allocation of '+ CAST(CAST([TotalAllocation] * 100 AS DECIMAL(6,2)) AS NVARCHAR(10)) + '% for Global Statistic: ' + GS.[Name] AS [Detail]
FROM [ob].[DimOBGlobalStatisticsPlan] AS GSP
    INNER JOIN (
                    SELECT 
                        [OBGlobalStatisticsPlanID],
                        [OBGlobalStatisticID], 
                        SUM([Allocation]) AS [TotalAllocation]
                    FROM [clientob].[FactGlobalStatisticsDeptMapping]
                    WHERE [IsReportable] = 1 AND [IsDeleted] = 0
                    GROUP BY [OBGlobalStatisticsPlanID], [OBGlobalStatisticID]
                ) AS ROLLUP
        ON GSP.[OBGlobalStatisticsPlanID] = ROLLUP.[OBGlobalStatisticsPlanID]
    INNER JOIN [ob].[DimOBGlobalStatistics] AS GS
        ON GS.[OBGlobalStatisticID] = ROLLUP.[OBGlobalStatisticID]
WHERE [TotalAllocation] <> 1;
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsDataWithoutDimensionMembers
/************************************************************
** Author: jgerber
** Create Date: 2014-09-18
** Description: Checks for global stat data that does not have dimension members
** Last Modified: 2014-09-18
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsDataWithoutDimensionMembers] as

--***Fact Global Statistics*********************************************
-- Department Dimension
	select
		Distinct
		0 as OBGlobalStatisticsPlanID,
		'Not Specified' as Model,
		'Has Global Statistics data for a Global Statistics Plan that no longer exists' as Detail
	from 
		[clientob].[FactGlobalStatistics] data with (readuncommitted)
		left join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Global Statistics Dimension
	select
		Distinct
		db.OBGlobalStatisticsPlanID,
		db.Name as Model,
		'Has Global Statistics data for a Global Statistic that no longer exists' as Detail
	from 
		[clientob].[FactGlobalStatistics] data with (readuncommitted)
		inner join[ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID
		left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID = data.OBGlobalStatisticID
	where 
		dim.MemberGUID is null
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsDepartmentAllocationOrphanedData
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Checks for global stat allocations that don't have dimension members
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsDepartmentAllocationOrphanedData] 
as


-- Department Dimension
	select
		Distinct
		0 as OBGlobalStatisticsPlanID,
		'Not Specified' as Model,
		'Has a Global Statistics Allocation for a Departmental Budget Plan that no longer exists' as Detail
	from 
		[clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted)
		left join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Account Dimension
	select
		Distinct
		dep.OBGlobalStatisticsPlanID,
		db.Name as Model,
		'Has a Global Statistics Allocation for an Account that no longer exists' as Detail
	from 
		[clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted)
		inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join [fw].[DimDepartment] dep with (readuncommitted) on dep.DepartmentID=db.DepartmentID
		left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID
	where 
		dim.MemberGUID is null	
		
UNION ALL		
		
-- Global Statistics Dimension
	select
		Distinct
		dep.OBGlobalStatisticsPlanID,
		db.Name as Model,
		'Has a Global Statistics Allocation for a Global Statistic that no longer exists' as Detail
	from 
		[clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted)
		inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		inner join [fw].[DimDepartment] dep with (readuncommitted) on dep.DepartmentID=db.DepartmentID
		left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.AccountID = data.AccountID and dim.DepartmentID=data.DepartmentID
	where 
		dim.MemberGUID is null
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsDuplicateFillins
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Finds all duplicate fillins in the OB Global Statistics model for the Account and Globals Statistics dimensions
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsDuplicateFillins] as

--ACCOUNTS
--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS

select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail

from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID
	inner join
(
select
	distinct DB.OBGlobalStatisticsPlanID, FI1.AccountID 
from
	[ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID
	inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
		and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID
where
	exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) 
	inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID
	inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID
	where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID
	and ME2.ExclusivityGroup=me.ExclusivityGroup)
	and ME.IsExclusive = 1 
) DUPES
	on DB.OBGlobalStatisticsPlanID = DUPES.OBGlobalStatisticsPlanID
	and DIM.AccountID = DUPES.AccountID
	and PH.AccountPHID<>0
	
union all

--GLOBAL STATISTICS
-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED
select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail

from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on FI.OBGlobalStatisticID = DIM.OBGlobalStatisticID
	inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID
	inner join
(
select
	distinct DB.OBGlobalStatisticsPlanID, FI1.OBGlobalStatisticID 
from
	[ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID
	inner join data.ScoreFillin_OBGlobalStatistics FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
		and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID
where
	exists (select 1 from data.ScoreFillin_OBGlobalStatistics FI2 with (readuncommitted) 
	inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID
	inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID
	where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID
	and ME2.ExclusivityGroup=me.ExclusivityGroup)
	and ME.IsExclusive = 1 
) DUPES
	on DB.OBGlobalStatisticsPlanID = DUPES.OBGlobalStatisticsPlanID
	and DIM.OBGlobalStatisticID = DUPES.OBGlobalStatisticID
	and PH.OBGlobalStatisticsPHID<>0
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsFillinCacheIssues
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID      Date        Author  WI      Description
** 1        2016-02-26  mholov  D-03407 Filtering out 'GM Blank' model template
** 2        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/
CREATE view [ob].[viewExceptionsGlobalStatsFillinCacheIssues] as

--Account
select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Account ' + DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank

union all

select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Account ' + DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted)
	inner join  data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimAccount DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where SF.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank

union all

--Global Statistics
select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Global Statistic ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all

select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Global Statistic ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join  [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where SF.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all


--Global Statistics Plan
select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Global Statistics Plan ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_OBGlobalStatisticsPlan] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [ob].[DimOBGlobalStatisticsPlan] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all

select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Global Statistics Plan ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join  [data].[ScoreFillin_OBGlobalStatisticsPlan] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [ob].[DimOBGlobalStatisticsPlan] DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where SF.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all


--Fiscal Year
select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync'  as Detail 
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
UNION ALL

select
	 DB.OBGlobalStatisticsPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync'  as Detail 
from
	ob.DimOBGlobalStatisticsPlan DB with (readuncommitted)
	inner join  [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimFiscalYear DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where SF.FillinMemberGUID is null
	and db.OBGlobalStatisticsPlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsFillinsExceedingMaxCount
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Finds all max fillin exceptions for Global Statistics
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsFillinsExceedingMaxCount] as
select
	DB.OBGlobalStatisticsPlanID,
	DB.Name as Model,
	'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Global Statistics in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail

from
	XPlan X with (readuncommitted)
	inner join [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from data.ScoreFillin_OBGlobalStatistics FI with (readuncommitted) inner join ob.DimOBGlobalStatisticsPH PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsInvalidDropdownSelection
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsInvalidDropdownSelection] as

select 
Distinct
DB.OBGlobalStatisticsPlanID,
DB.Name as Model,
'Global Statistic ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from [clientob].[FactGlobalStatisticsVar] fct with (readuncommitted)
inner join [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) on fct.OBGlobalStatisticsPlanID=db.OBGlobalStatisticsPlanID
inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on fct.OBGlobalStatisticID = DIM.OBGlobalStatisticID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsMissingGlobalStatistics
/****************************************************************************************************************
** Author: akowalski
** Create Date: 2014-06-29
** Description: Detects any statistics loaded into the global statistics import table that will go no where in global statistic sampling
** Last Modified: 2014-08-29
** GM Release: 2014.4
******************************************************************************************************************
** Change History
******************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		2017-01-11	srk		D-05373		Commented out a section that is a valid use case 
**											(departments with some stats that are driven off of history 
**											but some are global stats depending on the Global Statistics 
**											dimension setup/mapping)
**
*****************************************************************************************************************/
CREATE view [ob].[viewExceptionsGlobalStatsMissingGlobalStatistics] as

SELECT	
	distinct
	GSP.OBGlobalStatisticsPlanID,
	GSP.Name as Model,
	'Has data for Department ' + d.Name + ' and account ' + a.Name + ' but does not have a department-level global statistic configured' as Detail
FROM	
	[int].[FactGlobalStatistics] fct with (readuncommitted)
	inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID
	inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID
	inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
	left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID
	where a.IsGlobal=0 and gs.Name is null
	and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1
	and a.IsStat=1

	
union all

SELECT
	distinct
	GSP.OBGlobalStatisticsPlanID,
	GSP.Name as Model,
	'Has data for account ' + a.Name + ' but does not have an entity-level global statistic configured' as Detail
FROM	
	[int].[FactGlobalStatistics] fct with (readuncommitted) 
	inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID
	inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID
	inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
	left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=0
	where a.IsGlobal=1 and gs.Name is null
	and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1
	and a.IsStat=1
 
--CID 1 BEGIN--

--union all
--
--SELECT	
--	distinct
--	GSP.OBGlobalStatisticsPlanID,
--	GSP.Name as Model,
--	'Has data for Department ' + d.Name + ' and account ' + a.Name + ' but does not have a department-level global statistics configured' as Detail
--FROM	
--	[int].[FactStatistic] fct with (readuncommitted)
--	inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID
--	inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID
--	inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
--	left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID
--	where a.IsGlobal=0 and gs.Name is null
--	and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1
--	and a.IsStat=1

--CID 1 END--

union all

SELECT
	distinct
	GSP.OBGlobalStatisticsPlanID,
	GSP.Name as Model,
	'Has data for account ' + a.Name + ' but does not have an entity-level global statistic configured' as Detail
FROM	
	[int].[FactStatistic] fct with (readuncommitted) 
	inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID
	inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID
	inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID
	left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=0
	where a.IsGlobal=1 and gs.Name is null
	and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1
	and a.IsStat=1
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsMissingSelfFillin
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description: Displays any global statistics that are missing their self fill-in
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsGlobalStatsMissingSelfFillin] as

select Distinct
	DB.OBGlobalStatisticsPlanID,
	DB.Name as Model,
	'Global Statistics Plan ' + db.Name + ' is missing the self-fill-in'  as Detail
from 
	[ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted)
	left outer join [data].[ScoreFillin_OBGlobalStatisticsPlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='4c6057f6-854c-410c-9b51-4feb8e70c98e'
where 
	sf.FillinGUID is null
	and db.OBGlobalStatisticsPlanID<>0
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsOrphanedData
/************************************************************
** Author: akowalski
** Create Date: 2014-09-17
** Description: Checks for nonzero data that will not show up in the model because a fillin is missing
** Last Modified: 2014-09-17
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

Create view [ob].[viewExceptionsGlobalStatsOrphanedData] as

-- Stat data
	select
	Distinct
	db.OBGlobalStatisticsPlanID,
	db.Name as Model,
	'Has data in Statistic ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactGlobalStatistics] data with (readuncommitted)
		inner join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID
		inner join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID=data.OBGlobalStatisticID
		left outer join [data].[ScoreFillin_OBGlobalStatistics] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'b2ac7cce-90f5-47fc-a75e-c695ce64583d' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and db.OBGlobalStatisticsPlanID<>0
		and dim.OBGlobalStatisticID<>0
GO


---------------------------------------------

-- ob.viewExceptionsGlobalStatsProjectedEqualYTD
/************************************************************
** Author: jgerber
** Create Date: 2015-01-18
** Description:Compares Projected total and YTD to determine if anything is being projected in the non-closed months, indicates potential errors
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

create view [ob].[viewExceptionsGlobalStatsProjectedEqualYTD] as


select 
Distinct
DB.OBGlobalStatisticsPlanID,
DB.Name as Model,
'Has projected = YTD for Global Statistics: ' + Dim.Name + ' in section ' + PH.Name  as Detail
from [clientob].[FactGlobalStatistics] fct with (readuncommitted)
inner join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID=fct.OBGlobalStatisticsPlanID
inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on fct.OBGlobalStatisticID = DIM.OBGlobalStatisticID
inner join  [data].[ScoreFillin_OBGlobalStatistics] SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	and dim.MemberGUID=sf.FillinMemberGUID
inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.MonthsLoaded<>12
GO


---------------------------------------------

-- ob.viewExceptionsInvalidRosterBudgetData
CREATE VIEW ob.viewExceptionsInvalidRosterBudgetData
AS
/****************************************************************************************************
** Author: cbecker
** Create Date: 2017-02-09
** Description: Checks for data imported from roster budgeting with no fixed staffing fill-in
** Last Modified: 2017-02-09
** GM Release: 2017.1.2
****************************************************************************************************
** Change History
****************************************************************************************************
** CID		Date			Author		WI			Description
**
****************************************************************************************************/

SELECT distinct
	DepartmentCode = ddb.DepartmentCode,
	DepartmentalBudgetID = ddb.DepartmentalBudgetID, 
	DepartmentalBudget = ddb.Name,
	JobCodeID = djc.JobCodeID,
	JobCode = djc.Name,
	FTEs = SUM(FTEs),
	Dollars = SUM(Dollars),
	Detail = case
					when ddb.DepartmentalBudgetID is null
						then 'Departmental Budget does not exist'
					when ddb.OBActivePlans = 0
						then 'Departmental Budget has not been activated'
					when djc.JobCodeID is null
						then 'Job code does not exist'
					when sf.PlaceholderSectionMemberGUID is null
						then 'Job code does not exist in this model'
					else 'Job code is in the wrong section'
				end
FROM [fp].[RosterBudgetBasisResult] rb
	left join [fp].[BudgetConfig] bc
		on rb.BudgetConfigGUID = bc.BudgetConfigGUID
	left join [ob].[DimDepartmentalBudget] ddb
		on rb.DepartmentID = ddb.DepartmentID
	left join [fw].[DimJobCode] djc
		on rb.JobCodeID = djc.JobCodeID
	left join [fw].[DimPayCodeGroup] dpcg
		on rb.PayCodeGroupID = dpcg.PayCodeGroupID
	left join [data].[ScoreFillin_JobCode] sf
		on djc.MemberGUID = sf.FillinMemberGUID
		and ddb.MemberGUID = sf.ModelGUID
	left join [clientob].[FactStaffingPCNonReporting] fct
		on ddb.DepartmentalBudgetID = fct.DepartmentalBudgetID
		and djc.JobCodeID = fct.JobCodeID
		and dpcg.PayCodeGroupID = fct.PayCodeGroupID
		and bc.FiscalYearID = fct.FiscalYearID
where ddb.DepartmentalBudgetID is null or djc.JobCodeID is null or dpcg.PayCodeGroupID is null
and bc.IsActive = 1
GROUP BY 
	ddb.DepartmentCode,
	ddb.DepartmentalBudgetID, 
	ddb.Name,
	djc.JobCodeID,
	djc.Name,
	ddb.OBActivePlans,
	sf.PlaceholderSectionMemberGUID
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementAccountsNotBudgeted
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementAccountsNotBudgeted] AS


select 
	db.OBReimbursementPlanID, 
	db.Name as Model, 
	'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Account '+acc.Name+' but does not have a budget' as Detail

from [clientob].[FactReimbursementAccount] fa
inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID
inner join [fw].[DimAccount] acc on acc.AccountID=fa.AccountID
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID
where 
	FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
	and TimeClassID=1
	and Total<>0
	and acc.AccountID<>0
	and not (acc.OBIsDefined=1 and acc.OBAccountPHID=0 and acc.OBStatModelSectionID=0)
	and db.OBReimbursementPlanID<>0
	and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor)
	and not exists 
		(select 
			1 
		from 
			[clientob].[FactReimbursementAccount] fa2
		where 
			FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
			and TimeClassID=2 
			and Total<>0 
			and fa2.OBReimbursementPlanID=fa.OBReimbursementPlanID 
			and fa2.AccountID=fa.AccountID
			and fa2.UnitTypeID=fa.UnitTypeID)
group by
	db.OBReimbursementPlanID, 
	db.Name,
	ut.Name,
	acc.Name
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementAllocationsNot100Pct
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Checks that Account Allocation is 100% for each account in Allocation table
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementAllocationsNot100Pct] as


SELECT 
DB.OBReimbursementPlanID,
DB.Name as Model,
'Has Budget Allocation Not Equal to 1.0000 for Account: ' + Dim.Name + ' Allocation = ' + Cast(round(SUM(BudgetAllocation),4) as nvarchar(max)) as Detail
from [clientob].[FactReimbursementDeptMapping] fct with (readuncommitted)
inner join [ob].[DimOBReimbursementPlan] DB with (readuncommitted) on fct.OBReimbursementPlanID=DB.OBReimbursementPlanID
inner join [fw].[DimDepartment] md  with (readuncommitted) on fct.DepartmentID=md.DepartmentID
inner join [ob].[DimDepartmentalBudget] D  with (readuncommitted) on md.DepartmentID=D.DepartmentID
inner join [fw].[DimAccount] Dim with (readuncommitted)  on fct.AccountID=Dim.AccountID
Group by fct.AccountID, Dim.Name, DB.OBReimbursementPlanID, DB.Name
Having SUM(BudgetAllocation)<>1

Union All

SELECT 
DB.OBReimbursementPlanID,
DB.Name as Model,
'Has Projection Allocation Not Equal to 1.0000 for Account: ' + Dim.Name + ' Allocation = ' + Cast(round(SUM(ProjectionAllocation),4) as nvarchar(max)) as Detail
from [clientob].[FactReimbursementDeptMapping] fct with (readuncommitted)
inner join [ob].[DimOBReimbursementPlan] DB with (readuncommitted) on fct.OBReimbursementPlanID=DB.OBReimbursementPlanID
inner join [fw].[DimDepartment] md  with (readuncommitted) on fct.DepartmentID=md.DepartmentID
inner join [ob].[DimDepartmentalBudget] D  with (readuncommitted) on md.DepartmentID=D.DepartmentID
inner join [fw].[DimAccount] Dim with (readuncommitted)  on fct.AccountID=Dim.AccountID
Group by fct.AccountID, Dim.Name, DB.OBReimbursementPlanID, DB.Name
Having SUM(ProjectionAllocation)<>1
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementDataWithoutDimensionMembers
/************************************************************
** Author: jgerber
** Create Date: 2014-09-18
** Description: Checks for reimbursement data that does not have dimension members
** Last Modified: 2014-09-18
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

create view [ob].[viewExceptionsReimbursementDataWithoutDimensionMembers] as

--***Fact Reimbursement Account*********************************************
-- Reimbursement Plan Dimension
	select
		Distinct
		0 as OBReimbursementPlanID,
		'Not Specified' as Model,
		'Has Reimbursement Account data for a Reimbursement plan that no longer exists' as Detail
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Account Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement Account data for an Account that no longer exists' as Detail
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID
	where 
		dim.MemberGUID is null	
		
UNION ALL	
		
-- Patient Reimbursement Group Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement Account data for a Patient Reimbursement Group that no longer exists' as Detail
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
	where 
		dim.MemberGUID is null			

UNION ALL

--***Fact Reimbursement *********************************************
-- Reimbursement Plan Dimension
	select
		Distinct
		0 as OBReimbursementPlanID,
		'Not Specified' as Model,
		'Has Reimbursement data for a Reimbursement plan that no longer exists' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Forecast Detail Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement data for a Forecast Detail that no longer exists' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null	
		
UNION ALL	
		
-- Patient Reimbursement Group Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement data for a Patient Reimbursement Group that no longer exists' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
	where 
		dim.MemberGUID is null			
				

UNION ALL	
		
-- Payor Group Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement data for a Payor Group that no longer exists' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID
	where 
		dim.MemberGUID is null			
				
UNION ALL	
		
-- Payor Dimension
	select
		Distinct
		db.OBReimbursementPlanID,
		db.Name as Model,
		'Has Reimbursement data for a Payor that no longer exists' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID
	where 
		dim.MemberGUID is null
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementDuplicateFillins
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Finds all duplicate fillins in the Reimbursement model for the Account, Employee, Job Code, and Pay Code Group dimensions
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/


CREATE view [ob].[viewExceptionsReimbursementDuplicateFillins] as

--ACCOUNTS
--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS

select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail

from
	[ob].[DimOBReimbursementPlan] DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID
	inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID
	inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID
	inner join
(
select
	distinct DB.OBReimbursementPlanID, FI1.AccountID
from
	[ob].[DimOBReimbursementPlan] DB with (readuncommitted)
	inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID
	inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID
	inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
		and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID
where
	exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) 
	inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID
	inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID
	where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID
	and ME2.ExclusivityGroup=me.ExclusivityGroup)
	and ME.IsExclusive = 1 
) DUPES
	on DB.OBReimbursementPlanID = DUPES.OBReimbursementPlanID
	and DIM.AccountID = DUPES.AccountID
	and PH.AccountPHID<>0
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementEntityAndDepartmentNotEqual
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Show entities where total reimbursement model deductions dont match the final allocated deductions in Dept
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementEntityAndDepartmentNotEqual]  as


--PROJECTED

Select
	REIMB.OBReimbursementPlanID,
	REIMB.Model,
	'Dept Proj. Budget Amt: ' + FORMAT(DEPT.Total, 'C', 'en-us') 
	+ ' Reimb Model Proj. Amt: ' +FORMAT(REIMB.TOTAL, 'C', 'en-us')
	+ ' Department: ' + REIMB.Dept + ' Account: ' + REIMB.Acct  as Detail
FROM	
	(select 	
		rp.OBReimbursementPlanID,
		rp.Name as Model,
		db.DepartmentalBudgetID,
		ma.AccountID,
		SUM(rm.Month01 + rm.Month02 + rm.Month03 + rm.Month04 + rm.Month05 + rm.Month06 + rm.Month07 + rm.Month08 + rm.Month09 + rm.Month10 + rm.Month11 + rm.Month12) as Total,
		md.Name as Dept,
		ma.Name as Acct
	from 
	[clientob].[viewFactReimbursementMapping] rm
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID
	inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID
	inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID
	inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID
	where rm.TimeClassID IN(12) AND rm.FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') 	
	Group by
		rp.OBReimbursementPlanID,
		db.DepartmentalBudgetID,
		ma.AccountID,
		rp.Name,
		md.Name,
		ma.Name) As REIMB		
INNER JOIN
	(select 	
		rp.OBReimbursementPlanID,
		rp.Name as Model,
		db.DepartmentalBudgetID,
		ma.AccountID,
		SUM(rm.Total) as Total,
		md.Name as Dept,
		ma.Name as Acct
	from 
	[clientob].[FactAccount] rm
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID
	inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID
	inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID
	inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID
	where rm.TimeClassID IN(12) AND rm.FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
	Group by
		rp.OBReimbursementPlanID,
		db.DepartmentalBudgetID,
		ma.AccountID,
		rp.Name,
		md.Name,
		ma.Name) AS DEPT
ON REIMB.AccountID=DEPT.AccountID AND REIMB.DepartmentalBudgetID=DEPT.DepartmentalBudgetID
Where ROUND(DEPT.Total,0)<>ROUND(REIMB.Total,0)

UNION ALL

--BUDGETED

Select
	REIMB.OBReimbursementPlanID,
	REIMB.Model,
	'Dept Budg. Budget Amt: ' + FORMAT(DEPT.Total, 'C', 'en-us') 
	+ ' Reimb Model Budg. Amt: ' +FORMAT(REIMB.TOTAL, 'C', 'en-us')
	+ ' Department: ' + REIMB.Dept + ' Account: ' + REIMB.Acct  as Detail
FROM	
	(select 	
		rp.OBReimbursementPlanID,
		rp.Name as Model,
		db.DepartmentalBudgetID,
		ma.AccountID,
		SUM(rm.Month01 + rm.Month02 + rm.Month03 + rm.Month04 + rm.Month05 + rm.Month06 + rm.Month07 + rm.Month08 + rm.Month09 + rm.Month10 + rm.Month11 + rm.Month12) as Total,
		md.Name as Dept,
		ma.Name as Acct
	from 
	[clientob].[viewFactReimbursementMapping] rm
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID
	inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID
	inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID
	inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID
	where rm.TimeClassID IN(2) AND rm.FiscalYearID = (select Setting + 1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') 	
	Group by
		rp.OBReimbursementPlanID,
		db.DepartmentalBudgetID,
		ma.AccountID,
		rp.Name,
		md.Name,
		ma.Name) As REIMB		
INNER JOIN
	(select 	
		rp.OBReimbursementPlanID,
		rp.Name as Model,
		db.DepartmentalBudgetID,
		ma.AccountID,
		SUM(rm.Total) as Total,
		md.Name as Dept,
		ma.Name as Acct
	from 
	[clientob].[FactAccount] rm
	inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID
	inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID
	inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID
	inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID
	inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID
	where rm.TimeClassID IN(2) AND rm.FiscalYearID = (select Setting + 1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
	Group by
		rp.OBReimbursementPlanID,
		db.DepartmentalBudgetID,
		ma.AccountID,
		rp.Name,
		md.Name,
		ma.Name) AS DEPT
ON REIMB.AccountID=DEPT.AccountID AND REIMB.DepartmentalBudgetID=DEPT.DepartmentalBudgetID
Where ROUND(DEPT.Total,0)<>ROUND(REIMB.Total,0)
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementFillinCacheIssues
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID      Date        Author  WI      Description
** 1        2016-02-26  mholov  D-03407 Filtering out 'GM Blank' model template
** 2        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementFillinCacheIssues] as
--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match

--Account
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Account ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank


union all

--Payor
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Payor ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_Payor FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimPayor DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all

--PayorGroup
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for PayorGroup ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_PayorGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimPayorGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank


union all

--PatientReimbursementGroup
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for PatientReimbursementGroup ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_PatientReimbursementGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimPatientReimbursementGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank

union all

--OB Forecast Detail
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for OB Forecast Detail ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_OBForecastDetail FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join ob.DimOBForecastDetail DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all

--OB Departmental Budget
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for OB Reimbursement Plan ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_OBReimbursementPlan] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join ob.DimOBReimbursementPlan DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
union all

--Fiscal Year
select
	 DB.OBReimbursementPlanID,
	 DB.Name as Model,
	 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync'  as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
--==================== BEGIN CID 1 =====================
	and db.OBReimbursementPlanID<>0
--===================== END CID 1 ======================
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementFillinsExceedingMaxCount
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Check Max Counts for Reimbursement Model
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementFillinsExceedingMaxCount] as

--ACCOUNT
select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Has ' + cast((select COUNT(*) from data.ScoreFillin_Account FI with (readuncommitted) inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Accounts in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail

from
	XPlan X with (readuncommitted)
	inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from data.ScoreFillin_Account FI with (readuncommitted) inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]

union all


--Payor Group
select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_PayorGroup] FI with (readuncommitted) inner join [fw].[DimPayorGroupPH] PH with (readuncommitted) on FI.PayorGroupPHID = PH.PayorGroupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Payor Groups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
	XPlan X with (readuncommitted)
	inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from data.ScoreFillin_PayorGroup FI with (readuncommitted) inner join fw.DimPayorGroupPH PH with (readuncommitted) on FI.PayorGroupPHID = PH.PayorGroupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]

union all


--Payor
select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_Payor] FI with (readuncommitted) inner join [fw].[DimPayorPH] PH with (readuncommitted) on FI.PayorPHID = PH.PayorPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Payor in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
	XPlan X with (readuncommitted)
	inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from data.ScoreFillin_Payor FI with (readuncommitted) inner join fw.DimPayorPH PH with (readuncommitted) on FI.PayorPHID = PH.PayorPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]
	
	
union all


--PatientReimbursementGroup
select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_PatientReimbursementGroup] FI with (readuncommitted) inner join [fw].[DimPatientReimbursementGroupPH] PH with (readuncommitted) on FI.PatientReimbursementGroupPHID = PH.PatientReimbursementGroupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Patient Reimbursement Group in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail
from
	XPlan X with (readuncommitted)
	inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from data.ScoreFillin_PatientReimbursementGroup FI with (readuncommitted) inner join fw.DimPatientReimbursementGroupPH PH with (readuncommitted) on FI.PatientReimbursementGroupPHID = PH.PatientReimbursementGroupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementInvalidDropdownSelection
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/



CREATE view [ob].[viewExceptionsReimbursementInvalidDropdownSelection] as
--Accounts
select 
Distinct
DB.OBReimbursementPlanID,
DB.Name as Model,
'Account ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from [clientob].[FactReimbursementAccountVar] fct with (readuncommitted)
inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID
inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''

Union all


--Payor
select 
Distinct
DB.OBReimbursementPlanID,
DB.Name as Model,
'Account ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from [clientob].[FactReimbursementVar] fct with (readuncommitted)
inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID
inner join [fw].[DimPayor] DIM with (readuncommitted) on fct.PayorID = DIM.PayorID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''

Union all

--PayorGroup
select 
Distinct
DB.OBReimbursementPlanID,
DB.Name as Model,
'Account ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from [clientob].[FactReimbursementVar] fct with (readuncommitted)
inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID
inner join [fw].[DimPayorGroup] DIM with (readuncommitted) on fct.PayorGroupID = DIM.PayorGroupID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementMissingDepartmentAllocations
CREATE VIEW [ob].[viewExceptionsReimbursementMissingDepartmentAllocations] AS
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Checks for departments mapped to a reimbursement model with no rows in the allocation table
** Last Modified: 2017-08-22
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
** 2		08/22/2017  AI/cbb	D5967	added fiscal year and timeclass filters
*************************************************************/

	SELECT DISTINCT 
		rp.OBReimbursementPlanID,
		rp.NAME AS Model,
		'Department missing From Reimbursement Allocation: ' + db.NAME AS Detail
	FROM [clientob].[FactAccount] fa WITH (READUNCOMMITTED)
		INNER JOIN [ob].[DimDepartmentalBudget] db WITH (READUNCOMMITTED) ON fa.DepartmentalBudgetID = db.DepartmentalBudgetID
		INNER JOIN [fw].[DimDepartment] md WITH (READUNCOMMITTED) ON md.DepartmentID = db.DepartmentID
		INNER JOIN [ob].[DimOBReimbursementPlan] rp WITH (READUNCOMMITTED) ON rp.OBReimbursementPlanID = md.OBReimbursementPlanID
		INNER JOIN [data].[ScoreFillin_Account] ma WITH (READUNCOMMITTED) ON fa.AccountID = ma.AccountID AND db.MemberGUID = ma.ModelGUID
	WHERE 1=1
		and md.OBReimbursementPlanID <> 0
		AND fa.Total <> 0
-- CID 2 begin
		AND fa.FiscalYearID = (Select Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year')
		and fa.TimeClassID = 1
-- CID 2 end
		AND ma.AccountPHID IN (
			4 --Deductions
			,484 --Deductions - Charity and Bad Debt
			,481 --Deductions - Reimbursement
			)
		AND NOT EXISTS (
			SELECT 1
			FROM [clientob].[FactReimbursementDeptMapping] FI WITH (READUNCOMMITTED)
			WHERE FI.DepartmentID = DB.DepartmentID
				AND FI.OBReimbursementPlanID = rp.OBReimbursementPlanID
			)
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementMissingNotSpecifiedFillins
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Finds missing not specified fill-ins for the Reimbursement Model
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementMissingNotSpecifiedFillins] as
select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Payor Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_Payor] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayorID = 0 and FI.PayorPHID = 0)
	and DB.OBReimbursementPlanID != 0

union all

select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Payor Group Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_PayorGroup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayorGroupID = 0 and FI.PayorGroupPHID = 0)
	and DB.OBReimbursementPlanID != 0

union all

select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Patient Reimbursement Group Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_PatientReimbursementGroup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PatientReimbursementGroupID = 0 and FI.PatientReimbursementGroupPHID = 0)
	and DB.OBReimbursementPlanID != 0
	
union all

select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified OB Forecast Detail Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.OBForecastDetailID = 0 and FI.OBForecastDetailPHID = 0)
	and DB.OBReimbursementPlanID != 0
	
union all

select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Account Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_Account] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = 0 and FI.AccountPHID = 0)
	and DB.OBReimbursementPlanID != 0
	
union all

select
	DB.OBReimbursementPlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Fiscal Year Fill-in' as Detail
from
	ob.DimOBReimbursementPlan DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.FiscalYearID = 0 and FI.FiscalYearPHID = 0)
	and DB.OBReimbursementPlanID != 0
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementMissingSelfFillin
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Displays any Reimbusrement Budgets that are missing their self fill-in
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementMissingSelfFillin] as

select 
Distinct
DB.OBReimbursementPlanID,
DB.Name as Model,
'Reimbursement Budget ' + db.Name + ' is missing the self-fill-in'  as Detail
from ob.DimOBReimbursementPlan DB with (readuncommitted)
left outer join [data].[ScoreFillin_OBReimbursementPlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='4f0371d7-3d03-4320-9d83-413eb6105076'
where sf.FillinGUID is null
and db.OBReimbursementPlanID<>0
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementOrphanedData
/**************************************************************************************************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Check For Non Zero Data that will not show in model because a fillin is missing
** Last Modified: 2017-01-12
** GM Release: 2015.2
****************************************************************************************************************************************************
** Change History
****************************************************************************************************************************************************
** CID		Date		Author	WI		Description
** 1		2017-01-12	srk		D-05196	Exception will only display missing dollar accounts because not all volume accounts need to be filled in
**
***************************************************************************************************************************************************/

CREATE view [ob].[viewExceptionsReimbursementOrphanedData] as

-- Account data
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in Account ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join fw.DimAccount dim with (readuncommitted) on dim.AccountID = data.AccountID 
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'77A0029B-F072-4ED6-8BFC-89BCFD6ED049' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and db.OBReimbursementPlanID<>0
		and dim.AccountID<>0
		and data.UnitTypeID = 34 -- Only Dollars

UNION ALL

-- OB Forecast Detail
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in for OB Forecast Detail Member ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'45ef7590-f41c-4ea6-911e-03fe33a4e09f' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and data.TimeClassID = 1
		and db.OBReimbursementPlanID<>0
		and dim.OBForecastDetailID<>0

UNION ALL

-- Payor Group
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in for Payor Group ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'2d36244f-b97e-4787-99bd-2d75a499c4d8' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')
		and data.TimeClassID = 1
		and db.OBReimbursementPlanID<>0
		and dim.PayorGroupID<>0

UNION ALL

-- Payor
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in for Payor ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and data.TimeClassID = 1
		and db.OBReimbursementPlanID<>0
		and dim.PayorID<>0

UNION ALL

-- PatientReimbursementGroup
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in for Patient Reimbursement Group ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')
		and data.TimeClassID = 1
		and db.OBReimbursementPlanID<>0
		and dim.PatientReimbursementGroupID<>0
		
UNION ALL

-- PatientReimbursementGroup
	select
	Distinct
	db.OBReimbursementPlanID,
	db.Name as Model,
	'Has data in for Patient Reimbursement Group ' + dim.Name+ ' but it is not filled in' as Detail
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		inner join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
		left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
			and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified
	where 
		sf.FillinGUID is null
		and data.Total <> 0	
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and data.TimeClassID = 1
		and db.OBReimbursementPlanID<>0
		and dim.PatientReimbursementGroupID<>0
GO


---------------------------------------------

-- ob.viewExceptionsReimbursementProjectedEqualYTD
/************************************************************
** Author: blewis
** Create Date: 2015-01-15
** Description: Compares Projected total and YTD to determine of the anything is being projected in the non-closed months, indicates potential errors
** Last Modified: 2015-01-15
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		
**
*************************************************************/

CREATE view [ob].[viewExceptionsReimbursementProjectedEqualYTD] as


-- Account Data
select 
Distinct
DB.OBReimbursementPlanID,
DB.Name as Model,
'Has projected = YTD for Account: ' + Dim.Name + ' in section ' + PH.Name  as Detail
from [clientob].[FactReimbursementAccount] fct with (readuncommitted)
inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID=fct.OBReimbursementPlanID
inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID
inner join  data.ScoreFillin_Account SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	and dim.MemberGUID=sf.FillinMemberGUID
inner join ob.DimAccountPH PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID
where fct.datatypeid=3
and fct.YTD=fct.Total
and fct.TimeClassID=12
and fct.Total<>0
and fct.MonthsLoaded<>12
GO


---------------------------------------------

-- ob.viewExceptionsRosterBudgetDataNotInModel
CREATE VIEW ob.viewExceptionsRosterBudgetDataNotInModel
AS
/****************************************************************************************************
** Author: cbecker
** Create Date: 2017-01-23
** Description: Checks for data imported from roster budgeting with no fixed staffing fill-in
** Last Modified: 2017-01-23
** GM Release: 2017.1.2
****************************************************************************************************
** Change History
****************************************************************************************************
** CID		Date			Author		WI			Description
**
****************************************************************************************************/
select distinct
	DepartmentCode = ddb.DepartmentCode,
	DepartmentalBudgetID = ddb.DepartmentalBudgetID, 
	DepartmentalBudget = ddb.Name,
	JobCodeID = djc.JobCodeID,
	JobCode = djc.Name,
	Detail = case
					when ddb.DepartmentalBudgetID is null
						then 'Departmental Budget does not exist'
					when ddb.OBActivePlans = 0
						then 'Departmental Budget has not been activated'
					when djc.JobCodeID is null
						then 'Job code does not exist'
					when sf.PlaceholderSectionMemberGUID is null
						then 'Job code does not exist in this model'
					else 'Job code is in the wrong section'
				end
from [fp].[RosterBudgetBasisResult] rb
	inner join [fp].[BudgetConfig] bc
		on rb.BudgetConfigGUID = bc.BudgetConfigGUID
	left join [ob].[DimDepartmentalBudget] ddb
		on rb.DepartmentID = ddb.DepartmentID
	left join [fw].[DimJobCode] djc
		on rb.JobCodeID = djc.JobCodeID
	left join [fw].[DimPayCodeGroup] dpcg
		on rb.PayCodeGroupID = dpcg.PayCodeGroupID
	left join [data].[ScoreFillin_JobCode] sf
		on djc.MemberGUID = sf.FillinMemberGUID
		and ddb.MemberGUID = sf.ModelGUID
	left join [clientob].[FactStaffingPCNonReporting] fct
		on ddb.DepartmentalBudgetID = fct.DepartmentalBudgetID
		and djc.JobCodeID = fct.JobCodeID
		and dpcg.PayCodeGroupID = fct.PayCodeGroupID
		and bc.FiscalYearID = fct.FiscalYearID
where 1=1
	and fct.RowID is null
	and bc.IsActive = 1
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineDataWithoutDimensionMembers
/************************************************************
** Author: jgerber
** Create Date: 2014-09-18
** Description: Checks for SL data that does not have dimension members
** Last Modified: 2014-09-18
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

create view [ob].[viewExceptionsServiceLineDataWithoutDimensionMembers] as

--***Fact Service Line*********************************************
-- Service Line Plan Dimension
	select
		Distinct
		0 as OBServiceLinePlanID,
		'Not Specified' as Model,
		'Has Service Line data for a Service Line plan that no longer exists' as Detail
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		left join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
	where 
		db.MemberGUID is null
		
UNION ALL	
		
-- Modeling Service Line Dimension
	select
		Distinct
		db.OBServiceLinePlanID,
		db.Name as Model,
		'Has Service Line data for a Modeling Service Line that no longer exists' as Detail
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
		left join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID
	where 
		dim.MemberGUID is null	
		
UNION ALL	
		
-- Forecast Detail Dimension
	select
		Distinct
		db.OBServiceLinePlanID,
		db.Name as Model,
		'Has Service Line data for a Forecast Detail that no longer exists' as Detail
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineDuplicateFillins
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Finds all duplicate fillins in the OB Service Line model
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
**
*************************************************************/

CREATE VIEW [ob].[viewExceptionsServiceLineDuplicateFillins] as

--Modeling Service Line

select
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join [data].[ScoreFillin_ModelingServiceLine] FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI1.ModelingServiceLinePHID = PH.ModelingServiceLinePHID
	inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on FI1.ModelingServiceLineID = DIM.ModelingServiceLineID
where exists
(select 1
from
	[data].[ScoreFillin_ModelingServiceLine] FI2 with (readuncommitted)
where
	FI1.ModelGUID = FI2.ModelGUID
	and FI1.ModelingServiceLineID = FI2.ModelingServiceLineID
	and FI1.ModelingServiceLinePHID != FI2.ModelingServiceLinePHID
)
and PH.ModelingServiceLinePHID<>0

union all

--Service Line Rollup

select
	DB.OBServiceLinePlanID,
	DB.Name as Model,
	DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join [data].[ScoreFillin_ServiceLineRollup] FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID
	inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI1.ServiceLineRollupPHID = PH.ServiceLineRollupPHID
	inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on FI1.ServiceLineRollupID = DIM.ServiceLineRollupID
where exists
(select 1
from
	[data].[ScoreFillin_ServiceLineRollup] FI2 with (readuncommitted)
where
	FI1.ModelGUID = FI2.ModelGUID
	and FI1.ServiceLineRollupID = FI2.ServiceLineRollupID
	and FI1.ServiceLineRollupPHID != FI2.ServiceLineRollupPHID
)
and PH.ServiceLineRollupPHID<>0
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineFillinCacheIssues
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
**  CID     Date        Author  WI      Description
**  1       2016-02-26  mholov  D-03407 Filtering out 'GM Blank' model template
**  2       2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsServiceLineFillinCacheIssues] as
--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match

--Modeling service line
select
	 DB.OBServiceLinePlanID,
	 DB.Name as Model,
	 'The fill-in cache for Account ' + DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBServiceLinePlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank

UNION ALL

--Service line Rollup
select
	 DB.OBServiceLinePlanID,
	 DB.Name as Model,
	 'The fill-in cache for Service Line Rollup ' + DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBServiceLinePlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
	
	
UNION ALL

--Fiscal Year
select
	 DB.OBServiceLinePlanID,
	 DB.Name as Model,
	 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBServiceLinePlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
 
 UNION ALL
 
 --OBForecast Detail
 
select
	 DB.OBServiceLinePlanID,
	 DB.Name as Model,
	 'The fill-in cache for Forecast Detail ' --+ DIM.Name + ' out of sync'  as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID
	left join [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID
		and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID
		and sf.FillinMemberGUID=FI.FillinMemberGUID
		and sf.PlaceholderIndex=FI.PlaceholderIndex
	inner join [ob].[DimOBForecastDetail] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID
	inner join XPlan P on DB.MemberGUID = P.PlanGUID
	where FI.FillinMemberGUID is null
	and db.OBServiceLinePlanID<>0
	and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineFillinsExceedingMaxCount
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Checks fillin counts > expansion count in the OB Service Line model
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE view [ob].[viewExceptionsServiceLineFillinsExceedingMaxCount] as

select
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI.ModelingServiceLinePHID = PH.ModelingServiceLinePHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Service Lines in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail

from
	XPlan X with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI.ModelingServiceLinePHID = PH.ModelingServiceLinePHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]
	
Union all

select
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI.ServiceLineRollupPHID = PH.ServiceLineRollupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) as varchar(10))
	+ ' Service Line Rollups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail

from
	XPlan X with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID
	inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID
	inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID
	inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID
	inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID
where
	(select COUNT(*) from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI.ServiceLineRollupPHID = PH.ServiceLineRollupPHID where DB.MemberGUID = FI.ModelGUID and  PH.Name = SE.GlobalID) > SE.[Count]
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineInvalidDropdownSelection
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

Create view [ob].[viewExceptionsServiceLineInvalidDropdownSelection] as
--Service Line
select Distinct
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Service Line ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from 
	[clientob].[FactServiceLineVar] fct with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on fct.OBServiceLinePlanID=db.OBServiceLinePlanID
	inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on fct.ModelingServiceLineID = DIM.ModelingServiceLineID
where 
	fct.UnitTypeID=141
	and TextValue_Formula='x'
	and TextValue=''

Union all

--Service Line Rollup
select Distinct
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Service Line Rollup ' + Dim.Name + ' has an invalid drop-down box selection'  as Detail
from 
	[clientob].[FactServiceLineRollupVar] fct with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on fct.OBServiceLinePlanID=db.OBServiceLinePlanID
	inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on fct.ServiceLineRollupID = DIM.ServiceLineRollupID
where
	fct.UnitTypeID=141
	and TextValue_Formula='x'
	and TextValue=''
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineMissingNotSpecifiedFillins
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Finds all missing not specified fillins in the OB Service Line model
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE view [ob].[viewExceptionsServiceLineMissingNotSpecifiedFillins]
AS

--Service Line

select
	DB.OBServiceLinePlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Service line' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.ModelingServiceLineID = 0 and FI.ModelingServiceLinePHID = 0)
	and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1

Union all

--Service Line Rollup

select
	DB.OBServiceLinePlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Service Line Rollup' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.ServiceLineRollupID = 0 and FI.ServiceLineRollupPHID = 0)
	and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1


Union all

--OBForecastDetail

select
	DB.OBServiceLinePlanID,
	DB.Name as Model,
	'Is Missing the Not Specified OB Forecast Detail' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.OBForecastDetailID = 0 and FI.OBForecastDetailPHID = 0)
	and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1

Union all


--Fiscal Year

select
	DB.OBServiceLinePlanID,
	DB.Name as Model,
	'Is Missing the Not Specified Fiscal Year' as Detail
from
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
where
	not exists(select 1 from [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.FiscalYearID = 0 and FI.FiscalYearPHID = 0)
	and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineMissingSelfFillin
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Displays any service line models that are missing their self fill-in
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1        2016-08-10  kf      B-12543 FP - System Center Exception Management - Initial Framework
*************************************************************/

CREATE view [ob].[viewExceptionsServiceLineMissingSelfFillin] as

--Modeling service line
select 
Distinct
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Service line plan ' + db.Name + ' is missing the self-fill-in'  as Detail
from 
	[ob].[DimOBServiceLinePlan] DB with (readuncommitted)
	left outer join [data].[ScoreFillin_OBServiceLinePlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='811d09b3-431a-42f3-80d2-f100e27a1fdb'
where 
	sf.FillinGUID is null
	and db.OBServiceLinePlanID<>0
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineOrphanedData
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Checks for nonzero data that will not show up in the model because a fillin is missing
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE view [ob].[viewExceptionsServiceLineOrphanedData] as

-- Service line
select
Distinct
	db.OBServiceLinePlanID
	, db.Name as Model
	,'Has data in Service Line ' + dim.Name+ ' but it is not filled in' as Detail
from 
	[clientob].[FactServiceLine] data with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
	inner join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID
	left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
		and sf.PlaceholderSectionMemberGUID<>'d357335b-692a-4149-9d0b-f4fb231536c8' --not specified
where 
		sf.FillinGUID is null
		and data.Total <> 0	and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and db.OBServiceLinePlanID<>0
		and dim.ModelingServiceLineID<>0

UNION ALL

-- Service line Rollup
select
Distinct
	db.OBServiceLinePlanID
	, db.Name as Model
	,'Has data in Service Line ' + dim.Name+ ' but it is not filled in' as Detail
from 
	[clientob].[FactServiceLineRollupVar] data with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
	inner join [fw].[DimServiceLineRollup] dim with (readuncommitted) on dim.ServiceLineRollupID = data.ServiceLineRollupID
	left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID
		and sf.PlaceholderSectionMemberGUID<>'10802ab1-b116-48b5-a280-2b42083ab7bb' --not specified
where 
		sf.FillinGUID is null
		and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year')	
		and db.OBServiceLinePlanID<>0
		and dim.ServiceLineRollupID<>0
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineProjectedEqualYTD
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Compares Projected total and YTD to determine if anything is being projected in the non-closed months, indicates potential errors
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

Create view [ob].[viewExceptionsServiceLineProjectedEqualYTD] as

select Distinct
	DB.OBServiceLinePlanID
	,DB.Name as Model
	,'Has projected = YTD for Service Line: ' + Dim.ServiceLine + ' - ' + dim.MedicalSurgical + ' - ' + dim.AgeCohort + ' in section ' + dim.PatientClass  as Detail
from 
	[clientob].[FactServiceLine] fct with (readuncommitted)
	inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID=fct.OBServiceLinePlanID
	inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on fct.ModelingServiceLineID = DIM.ModelingServiceLineID
where 
	fct.datatypeid=3
	and fct.YTD=fct.Total
	and fct.TimeClassID=12
	and fct.Total<>0
GO


---------------------------------------------

-- ob.viewExceptionsServiceLineServiceLinesNotBudgeted
/************************************************************
** Author: cbecker
** Create Date: 2015-01-18
** Description: Service Lines without a Budget
** Last Modified: 2015-01-18
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
**
*************************************************************/

Create view ob.viewExceptionsServiceLineServiceLinesNotBudgeted
as

select 
	db.OBServiceLinePlanID
	,db.Name as Model
	,'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Service Line '+acc.Name+' but does not have a budget' as Detail

from [clientob].[FactServiceLine] fa
inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID
inner join [fw].[DimModelingServiceLine] acc on acc.ModelingServiceLineID=fa.ModelingServiceLineID
inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID
where 
	FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
	and TimeClassID=1
	and Total<>0
	and acc.ModelingServiceLineID<>0
	and fa.OBServiceLinePlanID<>0
	--and not (acc.OBIsDefined=1 and acc.OBAccountPHID=0 and acc.OBStatModelSectionID=0)
	and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor)
	and not exists 
		(select 
			1 
		from 
			[clientob].[FactServiceLine] fa2
		where 
			FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62')
			and TimeClassID=2 
			and Total<>0 
			and fa2.OBServiceLinePlanID=fa.OBServiceLinePlanID
			and fa2.ModelingServiceLineID=fa.ModelingServiceLineID
			and fa2.UnitTypeID=fa.UnitTypeID)
group by
	db.OBServiceLinePlanID
	,db.Name
	,ut.Name
	,acc.Name
GO


---------------------------------------------

-- ob.viewFactDepartmentPrimaryStatisticConfiguration
CREATE view ob.viewFactDepartmentPrimaryStatisticConfiguration as
select
f.RowID,
d.DepartmentalBudgetID,
f.AccountID,
convert(tinyint,f.Revenue) as Revenue,
convert(tinyint,f.Staffing) as Staffing,
convert(tinyint,f.NonStaffingExpense) as NonStaffingExpense,
f.IsDeleted,
f.HistoryItemGUID,
f.Version,
f.TransactionID
from [client].[FactDepartmentPrimaryStatisticConfiguration] f
inner join [ob].[DimDepartmentalBudget] d on f.DepartmentID=d.DepartmentID
GO


---------------------------------------------

-- ob.viewFactReportingMonthlyTargetComparision
CREATE view ob.viewFactReportingMonthlyTargetComparision as
/***************************************************************************************************************************************************************
** Author: akowalski
** Create Date: NA
** Description: Presents the post-model refresh data in the same format as the reconciliation targets are stored for comparison purposes
** Last Modified: 2014-06-12
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI			Description
** 1		2016-12-14	srk			D-04952		Removed unnecessary unions with factaccount to simplify the view, updated measure for YTD for current year
****************************************************************************************************************************************************************/

select total.EntityID,
total.FiscalMonthID,
total.FiscalYearID,
total.FinancialReportingID,
total.TimeClassID,
SUM(total.Amount) as Amount
from 
--------------------FACT REPORTING MONTHLY FOR FULL YEAR-------------------------
	(
	select db.EntityID,
	0 as FiscalMonthID,
	fct.FiscalYearID,
	fct.FinancialReportingID,
	fct.TimeClassID,
	fct.Total as Amount
	from [clientob].[FactReportingMonthly] fct
	inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
	inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D'
	where 1=1
	and fr.Type=0
	and fct.FiscalYearID = (Select DBS.Setting - 1 From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62')
	and fct.TimeClassID = 1

	union all 
	
	select db.EntityID,
	0 as FiscalMonthID,
	fct.FiscalYearID,
	fct.FinancialReportingID,
	fct.TimeClassID,
	fct.YTD as Amount
	from [clientob].[FactReportingMonthly] fct
	inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
	inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D'
	where 1=1
	and fr.Type=0
	and fct.FiscalYearID = (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62')
	and fct.TimeClassID = 1

	union all 

	select db.EntityID,
	0 as FiscalMonthID,
	fct.FiscalYearID,
	fct.FinancialReportingID,
	fct.TimeClassID,
	fct.Total as Amount
	from [clientob].[FactReportingMonthly] fct
	inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
	inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D'
	where 1=1
	and fr.Type=0
	and fct.FiscalYearID = (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62')
	and fct.TimeClassID = 2
	
--------------------FACT REPORTING MONTHLY FOR FULL YEAR-------------------------

	UNION ALL

--------------------FACT REPORTING MONTHLY BY MONTH FOR ACTUAL YTD---------------

		SELECT pv.EntityID,
		fm.FiscalMonthID,
		pv.FiscalYearID,
		pv.FinancialReportingID,
		pv.TimeClassID,
		pv.Amount
		      FROM (
			select db.EntityID,
			fct.FiscalYearID,
			fct.FinancialReportingID,
			1 as TimeClassID, -- only current year historicals will be by month
			fct.Month01, fct.Month02, fct.Month03, fct.Month04, fct.Month05, fct.Month06, fct.Month07, fct.Month08, fct.Month09, fct.Month10, fct.Month11, fct.Month12
			from [clientob].[FactReportingMonthly] fct
			inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
			inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D'
			where fr.Type=0 
			and fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month
			and fct.TimeClassID=12 -- only current year historicals will be by month (this is because projection data is stored by month for the YTD portion)
			) dta
		       unpivot (Amount for MonthColumnName in (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as pv
		       inner join fw.DimFiscalMonth fm with (readuncommitted) on pv.MonthColumnName = fm.MonthColumnName 
			   where fm.FiscalMonthID <= (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')

--------------------FACT REPORTING MONTHLY BY MONTH FOR ACTUAL YTD---------------


) total
group by
total.EntityID,
total.FiscalMonthID,
total.FiscalYearID,
total.FinancialReportingID,
total.TimeClassID
GO


---------------------------------------------

-- ob.viewFactReportingMonthlyTargetComparisionDetail
CREATE view ob.viewFactReportingMonthlyTargetComparisionDetail as
/************************************************************
** Author: akowalski
** Create Date: NA
** Description: Presents the post-model refresh data in the same format as the financial statement data source for comparison purposes
** Last Modified: 2014-06-12
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 	
*************************************************************/

	select 		fct.DepartmentalBudgetID,
	db.DepartmentID,
	0 as AccountID,
	fct.FinancialReportingID as FinancialReportingID,
	FiscalYearID,
	TimeClassID,
	Month01,
	Month02,
	Month03,
	Month04,
	Month05,
	Month06,
	Month07,
	Month08,
	Month09,
	Month10,
	Month11,
	Month12,
	YTD,
	Yearly,
	Total
	from [clientob].[FactReportingMonthly] fct
	inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
	where not (fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month
	and fct.TimeClassID=1)
		
union all

	select 
	DepartmentalBudgetID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	FiscalYearID,
	TimeClassID,
	Month01,
	Month02,
	Month03,
	Month04,
	Month05,
	Month06,
	Month07,
	Month08,
	Month09,
	Month10,
	Month11,
	Month12,
	0 as YTD,
	0 as Yearly,
	(YTD.Month01 + YTD.Month02 + YTD.Month03 + YTD.Month04 +
	YTD.Month05 + YTD.Month06 + YTD.Month07 + YTD.Month08 +
	YTD.Month09 + YTD.Month10 + YTD.Month11 + YTD.Month12) as Total
	from (
		select 	fct.DepartmentalBudgetID,
		db.DepartmentID,
		0 as AccountID,
		fct.FinancialReportingID as FinancialReportingID,
		FiscalYearID,
		1 as TimeClassID,
		case when mnth.Setting>=1 then Month01 else 0 end as Month01,
		case when mnth.Setting>=2 then Month02 else 0 end as Month02,
		case when mnth.Setting>=3 then Month03 else 0 end as Month03,
		case when mnth.Setting>=4 then Month04 else 0 end as Month04,
		case when mnth.Setting>=5 then Month05 else 0 end as Month05,
		case when mnth.Setting>=6 then Month06 else 0 end as Month06,
		case when mnth.Setting>=7 then Month07 else 0 end as Month07,
		case when mnth.Setting>=8 then Month08 else 0 end as Month08,
		case when mnth.Setting>=9 then Month09 else 0 end as Month09,
		case when mnth.Setting>=10 then Month10 else 0 end as Month10,
		case when mnth.Setting>=11 then Month11 else 0 end as Month11,
		case when mnth.Setting>=12 then Month12 else 0 end as Month12,
		YTD,
		Yearly,
		Total
		from [clientob].[FactReportingMonthly] fct
		inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID
		inner join [dbo].[DBSetting] mnth on mnth.name='OB_Months_Loaded'
		where fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month
		and fct.TimeClassID=12
	) YTD

	union all 

	select 
		f.DepartmentalBudgetID,
	d.DepartmentID,
	a.AccountID,
	a.OBDollarsFinancialReportingID as FinancialReportingID,
	FiscalYearID,
	TimeClassID,
	Month01,
	Month02,
	Month03,
	Month04,
	Month05,
	Month06,
	Month07,
	Month08,
	Month09,
	Month10,
	Month11,
	Month12,
	YTD,
	Yearly,
	Total
	from [clientob].[FactAccount] f
	inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID
	inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID
	inner join [fw].[DimAccount] a on a.AccountID = f.AccountID
	where f.UnitTypeID=34 and d.OBActivePlans=0
GO


---------------------------------------------

-- ob.viewFactStaffingPCUnpivoted
create View [ob].[viewFactStaffingPCUnpivoted] 
as
	select
		[DepartmentalBudgetID],
		[PayCodeGroupID],
		[PayCodeID],
		[JobCodeID],
		[EmployeeID],
		[FiscalYearID],
		[TimeClassID],
		[UnitTypeID],
		[DataTypeID],
		fm.[FiscalMonthID],
		[Value]
	from 
		(
			select * 
			from [clientob].[FactStaffingPC] source
		) as PIV
	UNPIVOT
		(
			VALUE for MonthColumnName IN 
			(
				[Month01]
				, [Month02]
				, [Month03]
				, [Month04]
				, [Month05]
				, [Month06]
				, [Month07]
				, [Month08]
				, [Month09]
				, [Month10]
				, [Month11]
				, [Month12]
			)
		) as f
		inner join fw.DimFiscalMonth fm 
			on f.MonthColumnName=fm.MonthColumnName
GO


---------------------------------------------

-- ob.viewFlexDriver
CREATE VIEW ob.viewFlexDriver
AS
/** Change History
**************************************************************
** CID		Date		Author	WI			Description
** 1		2014-09-03	GF		Initial Implementation
** 2		2022-06-21	KF		JAZZ-39078	PR Metrics Definition - Add Flex Driver for Daily calculations
*************************************************************/
	select 
		fd.FlexDriverGUID, 
		fd.Name, 
		fd.ScoreDatatableGUID, 
		fd.ParentDriverGUID, 
		fd.IsParentDriverFlexed, 
		fd.SortOrder, 
		fd.Tier, 
		fd.MeasureType, 
		fd.IsSameJobCode, 
		fd.IsSamePayCodeGroup,
		CAST(s.TimeFrameID as tinyint) TimeFrameID
	from 
		[ob].[FlexDriver] fd
		inner join
	(
	    select
			kl.DataTableGUID,
			MAX(case
				when a.SQLColumnName = 'DateID' then 2
				when a.SQLColumnName = 'PayPeriodID' then 1
				else 0 end) as TimeFrameID
		from [dbo].[ScoreDataTableKeyLink] kl
		inner join [dbo].[ScoreAttribute] a on a.AttributeGUID = kl.KeyGUID
		where
		    a.SQLColumnName in ('FiscalMonthID', 'PayPeriodID', 'DateID')
		GROUP BY kl.DataTableGUID	
	) s on s.DataTableGUID = fd.ScoreDatatableGUID
GO


---------------------------------------------

-- ob.viewPayrollVariabilityOverrideCacheForAllPayCodeGroupsGrouped
/*************************************************************
** Change History
**************************************************************
** CID		Date			Author		WI				Description
** 1      2023-11-21  	HV			JAZZ-40552  	Technical - Jazz - Create views for calculating targets with spreads for variable job-codes for Productive Hours-Standard metric for Pay Period/YTD
*************************************************************/

CREATE VIEW ob.viewPayrollVariabilityOverrideCacheForAllPayCodeGroupsGrouped
AS

SELECT 
	DepartmentID,
	JobCodeID,
	MAX(CASE WHEN Variability > 0 THEN 1 ELSE 0 END) as Variability
FROM ob.PayrollVariabilityOverrideCache
WHERE IsForAllPayCodeGroups = 1
GROUP BY DepartmentID, JobCodeID
GO


---------------------------------------------

-- ob.viewReconciliationDepartmentalBudgetIncomeStatement
CREATE view [ob].[viewReconciliationDepartmentalBudgetIncomeStatement] as
select 
d.EntityID as EntityID
, f.DepartmentalBudgetID
, d.Name as DepartmentalBudgetName
, dep.DepartmentID
, f.AccountID
, a.OBDollarsFinancialReportingID as [FinancialReportingID]
, f.TimeClassID
, f.FiscalYearID
, f.DataTypeID
, f.UnitTypeID
, f.[Month01]
, f.[Month02]
, f.[Month03]
, f.[Month04]
, f.[Month05]
, f.[Month06]
, f.[Month07]
, f.[Month08]
, f.[Month09]
, f.[Month10]
, f.[Month11]
, f.[Month12]
, f.[Total]
, f.[Yearly]
, f.[YTD]
from [clientob].[FactAccount] f
inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID
inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID
inner join [fw].[DimAccount] a on a.AccountID = f.AccountID
where f.UnitTypeID=34
GO


---------------------------------------------

-- ob.viewReconciliationDepartmentalBudgetStaffing
/************************************************************
** Author: akowalski
** Create Date: NA
** Description: The driving view for Staffing Data Reconciliation Screens in 
** Last Modified: 2014-10-15
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/
CREATE view [ob].[viewReconciliationDepartmentalBudgetStaffing]
AS 

-- Data that will actually show up in the model

SELECT	
	dept.EntityID as EntityID,
	budget.DepartmentalBudgetID,
	budget.Name as DepartmentalBudgetName,
	dept.DepartmentID,
	d.JobCodeID,
	pcg.PayCodeGroupID,
	d.PayCodeID,
	d.TimeClassID,
	d.FiscalYearID,
	d.FiscalMonthID,
	d.EmployeeID,
--	case 
--	when unittypeID='34' then unittypeID
--	when unittypeID<>'34' and pcg.ProductiveClass='Productive' then 148
--	when unittypeID<>'34' and pcg.ProductiveClass='Non-Productive' then 146
--	when unittypeID<>'34' and pcg.ProductiveClass='Differential' then 147
--	else 51 end as UnitTypeID,
	d.UnitTypeID,
	dt.DataTypeID,
	d.Value
FROM	
	[int].[FactStaffing] AS d  		
	inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID
	inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID
	inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid
	inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID
	inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID
	inner join fw.DimDataType dt on dt.Name='Input'
	inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year'
	inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID
	inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID
where e.IsProvider=0 
and pc.PayCodeGroupID<>0 and ((pc.IsDollarsIgnored=0 and d.UnitTypeid=34)
or (pc.IsHoursIgnored=0 and d.UnitTypeid<>34))
and d.fiscalyearID > (yr.Setting - 2)
and ((jc.IsProvider=0 and ent.OBIsUsingProviderComp=1)
or ent.OBIsUsingProviderComp=0)

-- Data that's suppressed because of job code configuration
union all 

SELECT	
	dept.EntityID as EntityID,
	budget.DepartmentalBudgetID,
	budget.Name as DepartmentalBudgetName,
	dept.DepartmentID,
	0 as JobCodeID,
	0 as PayCodeGroupID,
	d.PayCodeID,
	d.TimeClassID,
	d.FiscalYearID,
	d.FiscalMonthID,
	d.EmployeeID,
	d.UnitTypeID,
	dt.DataTypeID,
	d.Value
FROM	
	[int].[FactStaffing] AS d  		
	inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID
	inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID
	inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid
	inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID
	inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID
	inner join fw.DimDataType dt on dt.Name='Input'
	inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year'
	inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID
	inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID
where pc.PayCodeGroupID<>0 and ((pc.IsDollarsIgnored=0 and d.UnitTypeid=34)
or (pc.IsHoursIgnored=0 and d.UnitTypeid<>34))
and d.fiscalyearID > (yr.Setting - 2)
and (e.IsProvider=1 
or (jc.IsProvider=1 and ent.OBIsUsingProviderComp=1))

-- data that's suppressed because of pay code configuration
union all 

SELECT	
	dept.EntityID as EntityID,
	budget.DepartmentalBudgetID,
	budget.Name as DepartmentalBudgetName,
	dept.DepartmentID,
	0 as JobCodeID,
	0 as PayCodeGroupID,
	d.PayCodeID,
	d.TimeClassID,
	d.FiscalYearID,
	d.FiscalMonthID,
	d.EmployeeID,
	d.UnitTypeID,
	dt.DataTypeID,
	d.Value
FROM	
	[int].[FactStaffing] AS d  		
	inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID
	inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID
	inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid
	inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID
	inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID
	inner join fw.DimDataType dt on dt.Name='Input'
	inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year'
	inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID
	inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID
where e.IsProvider=0 
and d.fiscalyearID > (yr.Setting - 2)
and ((jc.IsProvider=0 and ent.OBIsUsingProviderComp=1)
or ent.OBIsUsingProviderComp=0)
and (pc.PayCodeGroupID=0 or (pc.IsDollarsIgnored=1 and d.UnitTypeid=34)
or (pc.IsHoursIgnored=1 and d.UnitTypeid<>34))
GO


---------------------------------------------

-- ob.viewReconciliationDepartmentalBudgetStatistics
create view [ob].[viewReconciliationDepartmentalBudgetStatistics] as
select 
d.EntityID as EntityID
, f.DepartmentalBudgetID
, d.Name as DepartmentalBudgetName
, dep.DepartmentID
, f.AccountID
, a.PatientClassID
, f.TimeClassID
, f.FiscalYearID
, f.DataTypeID
, f.UnitTypeID
, f.[Month01]
, f.[Month02]
, f.[Month03]
, f.[Month04]
, f.[Month05]
, f.[Month06]
, f.[Month07]
, f.[Month08]
, f.[Month09]
, f.[Month10]
, f.[Month11]
, f.[Month12]
, f.[Total]
, f.[Yearly]
, f.[YTD]
from [clientob].[FactAccount] f
inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID
inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID
inner join [fw].[DimAccount] a on a.AccountID = f.AccountID
where f.UnitTypeID<>34 and f.UnitTypeID<>0
GO


---------------------------------------------

-- ob.viewReconciliationRollingOBDollarsGLOnly
CREATE VIEW [ob].[viewReconciliationRollingOBDollarsGLOnly] as
select 
	ob.DepartmentalBudgetID as PlanID,
	ob.Name as PlanName,
	source.AccountID as AccountID,
	ma.AccountCode as Account,
	source.DepartmentID as DepartmentID,
	md.DepartmentCode as Department,
	0 as PatientTypeRollupID,
	'n/a' as PatientTypeRollup,
	ma.OBDollarsFinancialReportingID as FinancialReportingID,
		ma.OBDollarsFinancialReporting,

	ut.UnitTypeID as UnitTypeID,
	ut.Name as UnitType,
	source.TimeClassID as TimeClassID,
	source.TimeClassCode as TimeClass,
	source.FiscalYearID as FiscalYearID,
	source.FiscalYearCode as FiscalYear,
	source.FiscalMonthID as FiscalMonthID,
	source.FiscalMonthCode as FiscalMonthCode,
	(source.Value * isnull(ma.Inversion, 1)) as Value
from int.FactGL source (readuncommitted)
	Inner Join fw.DimAccount ma (readuncommitted) on ma.AccountID = source.AccountID
	Inner Join fw.DimDepartment md (readuncommitted) on md.DepartmentID = source.DepartmentID
	inner join ob.viewDimDepartmentalBudget ob on md.DepartmentID = ob.DepartmentID
	Inner Join fw.DimUnitType ut (readuncommitted) on ut.Name='Dollars'
where 
	md.DepartmentID<>0
	


Union All

select 
	ob.DepartmentalBudgetID as PlanID,
	ob.Name as PlanName,
	source.AccountID as AccountID,
	ma.AccountCode as Account,
	source.DepartmentID as DepartmentID,
	md.DepartmentCode as Department,
	0 as PatientTypeRollupID,
	GLRollup as PatientTypeRollup,
	ma.OBDollarsFinancialReportingID as FinancialReportingID,
	ma.OBDollarsFinancialReporting ,
	ut.UnitTypeID,
	ut.name as UnitType,
	source.TimeClassID as TimeClassID,
	source.TimeClassCode as TimeClass,
	source.FiscalYearID as FiscalYearID,
	source.FiscalYearCode as FiscalYear,
	source.FiscalMonthID as FiscalMonthID,
	source.FiscalMonthCode as FiscalMonthCode,
	source.Value as Value
from int.FactStatistic source (readuncommitted)
	Inner Join fw.DimAccount ma (readuncommitted) on ma.AccountID = source.AccountID and ma.IsStat =1
	--inner join fw.DimPatientType PT on PT.PatientTypeID = ma.PatientTypeID 
	--inner join fw.DimPatientTypeRollup PR on PR.PatientTypeRollupID = PT.PatientTypeRollupID
	Inner Join fw.DimDepartment md (readuncommitted) on md.DepartmentID = source.DepartmentID
	inner join ob.viewDimDepartmentalBudget ob (readuncommitted) on md.DepartmentID=md.DepartmentID
	inner join fw.DimUnitType ut on ut.Name ='Volume'
where 
	md.DepartmentID<>0
GO


---------------------------------------------

-- ob.viewReportAccountSnapshotData
/************************************************************
** Author: Joel Gerber
** Create Date: 2014-03-10
** Description: Reporting Data View for All OB Snapshot Reports
** Last Modified: 2014-03-10
** GM Release: NA (Customization)
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/
create view [ob].[viewReportAccountSnapshotData] as


select
	data.DepartmentalBudgetID,
	data.AccountID,
	FiscalYearID,
	TimeClassID,
	UnitTypeID,
	DataTypeID,
	acc.PatientTypeID,
	OBSnapshotID,
	Month01,
	Month02,
	Month03,
	Month04,
	Month05,
	Month06,
	Month07,
	Month08,
	Month09,
	Month10,
	Month11,
	Month12,
	data.MonthsLoaded,
	YTD,
	Yearly,
	Total
from
	ob.FactAccountSnapshot data
	inner join fw.DimAccount acc on acc.AccountID=data.AccountID
where
	acc.IsGlobal=0
GO


---------------------------------------------

-- ob.viewReportAccountWithStaffingDetail
create view [ob].[viewReportAccountWithStaffingDetail] 
as

-- Staffing Data
-------------------------------------------------------------------------------------------
	select
		DepartmentalBudgetID 	= vw.DepartmentalBudgetID,
		AccountID 				= vw.AccountID,
		JobCodeID				= vw.JobCodeID,
		PayCodeGroupID			= vw.PayCodeGroupID,
		FiscalYearID 			= vw.FiscalYearID,
		TimeClassID 			= vw.TimeClassID,
		UnitTypeID 				= vw.UnitTypeID,
		Month01 				= vw.Month01,
		Month02 				= vw.Month02,
		Month03 				= vw.Month03,
		Month04 				= vw.Month04,
		Month05 				= vw.Month05,
		Month06 				= vw.Month06,
		Month07 				= vw.Month07,
		Month08 				= vw.Month08,
		Month09 				= vw.Month09,
		Month10 				= vw.Month10,
		Month11 				= vw.Month11,
		Month12 				= vw.Month12,
		YTD 					= cmb.IsCY*vw.YTD,
		Total 					= vw.Total
	from [ob].[viewReportStaffingtoGLAccount] vw
		inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb
			on vw.TimeClassID=cmb.TimeClassID
			and vw.DataTypeID=cmb.DataTypeID
			and vw.FiscalYearID=cmb.FiscalYearID
		inner join [clientob].[FactAccount] fct
			on vw.DepartmentalBudgetID	= fct.DepartmentalBudgetID
			and vw.AccountID 			= fct.AccountID
			and vw.FiscalYearID 		= fct.FiscalYearID
			and vw.TimeClassID 			= fct.TimeClassID
			and vw.UnitTypeID 			= fct.UnitTypeID
			and vw.DataTypeID 			= fct.DataTypeID

UNION ALL

-- Non-Staffing Account Data
-------------------------------------------------------------------------------------------
	select
		DepartmentalBudgetID	= fct.DepartmentalBudgetID, 
		AccountID				= fct.AccountID, 
		JobCodeID				= 0,
		PayCodeGroupID			= 0,
		FiscalYearID 			= fct.FiscalYearID, 
		TimeClassID 			= fct.TimeClassID, 
		UnitTypeID 				= fct.UnitTypeID, 
		Month01 				= fct.Month01,
		Month02 				= fct.Month02,
		Month03 				= fct.Month03,
		Month04 				= fct.Month04,
		Month05 				= fct.Month05,
		Month06 				= fct.Month06,
		Month07 				= fct.Month07,
		Month08 				= fct.Month08,
		Month09 				= fct.Month09,
		Month10 				= fct.Month10,
		Month11 				= fct.Month11,
		Month12 				= fct.Month12,
		YTD 					= cmb.IsCY*fct.YTD,
		Total 					= fct.Total
	from [clientob].[FactAccount] fct
		inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb
			on fct.TimeClassID=cmb.TimeClassID
			and fct.DataTypeID=cmb.DataTypeID
			and fct.FiscalYearID=cmb.FiscalYearID
	where not exists
			(
				select 1
				from [ob].[viewReportStaffingtoGLAccount] vw
				where 1=1
					and fct.DepartmentalBudgetID 	= vw.DepartmentalBudgetID
					and fct.AccountID 				= vw.AccountID
					and fct.FiscalYearID 			= vw.FiscalYearID
					and fct.TimeClassID 			= vw.TimeClassID
					and fct.UnitTypeID 				= vw.UnitTypeID
					and fct.DataTypeID 				= vw.DataTypeID
			)

UNION ALL

-- GL Data Historical Input Data Discrepancy
-------------------------------------------------------------------------------------------
	select
		DepartmentalBudgetID 	= fct.DepartmentalBudgetID,
		AccountID 				= fct.AccountID,
		JobCodeID				= 0,
		PayCodeGroupID			= 0,
		FiscalYearID 			= fct.FiscalYearID,
		TimeClassID 			= fct.TimeClassID,
		UnitTypeID 				= fct.UnitTypeID,
		Month01 				= max(fct.Month01) - sum(vw.Month01),
		Month02 				= max(fct.Month02) - sum(vw.Month02),
		Month03 				= max(fct.Month03) - sum(vw.Month03),
		Month04 				= max(fct.Month04) - sum(vw.Month04),
		Month05 				= max(fct.Month05) - sum(vw.Month05),
		Month06 				= max(fct.Month06) - sum(vw.Month06),
		Month07 				= max(fct.Month07) - sum(vw.Month07),
		Month08 				= max(fct.Month08) - sum(vw.Month08),
		Month09 				= max(fct.Month09) - sum(vw.Month09),
		Month10 				= max(fct.Month10) - sum(vw.Month10),
		Month11 				= max(fct.Month11) - sum(vw.Month11),
		Month12 				= max(fct.Month12) - sum(vw.Month12),
		YTD 					= max(cmb.IsCY)*(max(fct.YTD ) - sum(vw.YTD)),
		Total 					= max(fct.Total ) - sum(vw.Total)
	from [clientob].[FactAccount] fct
		inner join [ob].[viewReportStaffingtoGLAccount] vw
			on fct.DepartmentalBudgetID = vw.DepartmentalBudgetID
			and fct.AccountID 			= vw.AccountID
			and fct.FiscalYearID 		= vw.FiscalYearID
			and fct.TimeClassID 		= vw.TimeClassID
			and fct.UnitTypeID 			= vw.UnitTypeID
			and fct.DataTypeID			= vw.DataTypeID
		inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb
			on fct.TimeClassID=cmb.TimeClassID
			and fct.DataTypeID=cmb.DataTypeID
			and fct.FiscalYearID=cmb.FiscalYearID
	where 1=1
		and (fct.DataTypeID = 4 or fct.TimeClassID = 12)
	group by
		fct.DepartmentalBudgetID,
		fct.AccountID,
		fct.FiscalYearID,
		fct.TimeClassID,
		fct.UnitTypeID
	having
		max(fct.Total) <> SUM(vw.Total)
GO


---------------------------------------------

-- ob.viewReportAccountWithStaffingDetail_Friendly
CREATE VIEW [ob].[viewReportAccountWithStaffingDetail_Friendly]
As

SELECT 
	md.DepartmentCode as [DepartmentCode]
	, md.Description as [DepartmentDescription]
	, md.Entity
	, md.EntityCode
	, md.DepartmentRollup1
	, md.DepartmentRollup2
	, md.DepartmentRollup3
	, md.DepartmentRollup4
	, md.DepartmentRollup5
	, md.DepartmentRollup6
	, a.AccountCode as [AccountCode]
	, a.Description as [AccountDescription]
	, a.GMAccountRollup1 as AccountRollup1
	, a.GMAccountRollup2 as AccountRollup2
	, a.GMAccountRollup3 as AccountRollup3
	, a.GMAccountRollup4 as AccountRollup4
	, a.GMAccountRollup5 as AccountRollup5
	, a.GMAccountRollup6 as AccountRollup6
	, a.[OBDollarsFinancialReportingLineName] as DollarsFinancialReportingLineName
	, a.[OBUnitsFinancialReportingLineName] as UnitsFinancialReportingLineName
	, jc.Name as [JobCode]
	, jcg.Name as [JobCodeGroup]
	, pcg.Name as [PayCodeGroup]
	, fy.Name as [FiscalYear]
	, tc.Name as [TimeClass]
	, ut.Name  as [UnitType]
	, [Month01]
	, [Month02]
	, [Month03]
	, [Month04]
	, [Month05]
	, [Month06]
	, [Month07]
	, [Month08]
	, [Month09]
	, [Month10]
	, [Month11]
	, [Month12]
	, [YTD]
	, [Total]
FROM [ob].[FactReportAccountWithStaffingDetail] r
INNER JOIN [fw].[DimAccount] a on r.AccountID=a.AccountID
INNER JOIN [ob].[DimDepartmentalBudget] d on r.DepartmentalBudgetID=d.DepartmentalBudgetID
INNER JOIN [fw].[DimDepartment] md on d.DepartmentID=md.DepartmentID
INNER JOIN [fw].[DimJobCode] jc on r.JobCodeID=jc.JobCodeID
INNER JOIN [fw].[DimJobCodeGroup] jcg on jc.JobCodeGroupID=jcg.JobCodeGroupID
INNER JOIN [fw].[DimPayCodeGroup] pcg on r.PayCodeGroupID=pcg.PayCodeGroupID
INNER JOIN [fw].[DimUnitType] ut on r.UnitTypeID=ut.UnitTypeID
INNER JOIN [fw].[DimTimeClass] tc on r.TimeClassID=tc.TimeClassID
INNER JOIN [fw].[DimFiscalYear] fy on r.FiscalYearID=fy.FiscalYearID
Where Total <> 0
GO


---------------------------------------------

-- ob.viewReportCDMRatios
/************************************************************
** Author: BL
** Create Date: 2014-11-13
** Description: Service Line to Department CDM Ratios for Reporting
** Last Modified: 2014-11-13
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID	Date		Author		WI		Description
**	1	
*************************************************************/
Create view [ob].[viewReportCDMRatios] as
select
	CDMRatio.FiscalYearID,
	B.DepartmentalBudgetID,
	CDMRatio.ModelingServiceLineID,
	CDMRatio.ChargeCodeID,
	ut.UnitTypeID,
	dt.DataTypeID,
	MSL.PatientClassID,
	CDMRatio.CurrentYear as [ProjectedRatio],
	CDMRatio.NextYear as [BudgetRatio],
	B.DepartmentalBudgetID as BudgID
from [clientob].[FactServiceLinetoDepartmentCDM] CDMRatio
inner join [ob].[DimDepartmentalBudget] B on B.DepartmentID = CDMRatio.DepartmentID
inner join [fw].[DimDepartment] D on D.DepartmentID = B.DepartmentID
inner join [ob].[DimOBServiceLinePlan] SLP on D.OBServiceLinePlanID=SLP.OBServiceLinePlanID
inner join [dbo].[DBSetting] DBS on DBS.Name = 'OB_Current_Year' and CDMRatio.FiscalYearID=DBS.Setting
inner join [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = CDMRatio.ModelingServiceLineID
inner join [fw].[DimUnitType] ut on ut.GlobalID='Units'
inner join fw.dimdatatype dt on dt.globalid='Input'
where CDMRatio.IsDeleted = 0 and  NOT (CDMRatio.CurrentYear=0 OR CDMRatio.NextYear=0)
GO


---------------------------------------------

-- ob.viewReportDepartmentBudgetModelToReconciliationTargetComparisionDetail
create view [ob].[viewReportDepartmentBudgetModelToReconciliationTargetComparisionDetail] as
/************************************************************
** Author: akowalski
** Create Date: 2014-06-12
** Description: Displays the department level detail for model to target comparisions
** Last Modified: 2014-06-12
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 	
*************************************************************/
select db.entityid,
f.DepartmentID,
f.FinancialReportingID,
f.TimeClassID,
f.FiscalYearID,
f.Month01,
f.Month02,
f.Month03,
f.Month04,
f.Month05,
f.Month06,
f.Month07,
f.Month08,
f.Month09,
f.Month10,
f.Month11,
f.Month12,
f.Total,
'Live' as [Type]
from [ob].[viewFactReportingMonthlyTargetComparisionDetail] f
inner join [ob].[DimDepartmentalBudget] db on f.DepartmentalBudgetID=db.DepartmentalBudgetID


union all

select db.entityid,
f.DepartmentID,
f.FinancialReportingID,
f.TimeClassID,
f.FiscalYearID,
f.Month01,
f.Month02,
f.Month03,
f.Month04,
f.Month05,
f.Month06,
f.Month07,
f.Month08,
f.Month09,
f.Month10,
f.Month11,
f.Month12,
f.Total,
'Target' as [Type]
from [clientob].[viewReportFinancialStatements] f
inner join [ob].[DimDepartmentalBudget] db on f.DepartmentalBudgetID=db.DepartmentalBudgetID
GO


---------------------------------------------

-- ob.viewReportDepartmentalBudgetExceptionsSummary
create view ob.viewReportDepartmentalBudgetExceptionsSummary as
/************************************************************
** Author: akowalski
** Create Date: 2014-04-30
** Description: Summarized OB department budget exceptions for dashboard
** Last Modified: 2014-04-30
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-02-19	DK		56588	Adding update statistics command
**
*************************************************************/

select 
e.OBExceptionsID,
sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open],
sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged
from [ob].[FactDepartmentBudgetExceptions] e
group by e.OBExceptionsID
GO


---------------------------------------------

-- ob.viewReportExceptionsDepartmentBudgetExceededProductivityTargets
/************************************************************
** Author: jgerber
** Create Date: 2013-11-17
** Description: Exception report to show which departments are over their productivity target
** Last Modified: 2014-10-07
** GM Release: 2015.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-10-07	JG				Renaming and adding to the exception summary report 
**
*************************************************************/
create view ob.viewReportExceptionsDepartmentBudgetExceededProductivityTargets

as

select 
	targ.DepartmentalBudgetID, 
	targ.BudgetName as Model,
	'Has '+cast(tot.Amount as Nvarchar(100))+' Hrs/UOS when the target is '+cast(targ.Amount as Nvarchar(100))+' Hrs/UOS for '+targ.TimeClassName+' '+targ.FiscalYearName as Detail
from	
	[clientob].[viewFactStaffingPCVar] targ
	inner join [clientob].[viewFactStaffingPCVar] tot 	on targ.DepartmentalBudgetID=tot.DepartmentalBudgetID and targ.TimeClassID=tot.TimeClassID and targ.UnitTypeID=tot.UnitTypeID and targ.FiscalYearID=tot.FiscalYearID
where 
	targ.AssumptionID=639 --Hours per UOS Target
	and tot.AssumptionID=640 --Hours per UOS
	and targ.Amount<tot.Amount
GO


---------------------------------------------

-- ob.viewReportFactGlobalStatisticMapping
/************************************************************
** Author: cbecker
** Create Date: NA
** Description:
** Last Modified: 2015-12-18
** GM Release: 2016.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author		WI		Description
** 	1 	   
*************************************************************/
Create view ob.viewReportFactGlobalStatisticMapping
as
-----------------------------------------------------
------------Allocated Global Statistics--------------
-----------------------------------------------------
	select 
		'Allocated' as Type,
		DepartmentalBudgetID,
		gp.OBGlobalStatisticsPlanID,
		dm.DepartmentID,
		gs.AccountID,
		dt.DataTypeID,
		TimeClassID,
		FiscalYearID,
		UnitTypeID,
		YTDAllocation,
		Allocation,
		Month01 = SUM(Month01*Allocation),
		Month02 = SUM(Month02*Allocation),
		Month03 = SUM(Month03*Allocation),
		Month04 = SUM(Month04*Allocation),
		Month05 = SUM(Month05*Allocation),
		Month06 = SUM(Month06*Allocation),
		Month07 = SUM(Month07*Allocation),
		Month08 = SUM(Month08*Allocation),
		Month09 = SUM(Month09*Allocation),
		Month10 = SUM(Month10*Allocation),
		Month11 = SUM(Month11*Allocation),
		Month12 = SUM(Month12*Allocation) 
	from [clientob].[FactGlobalStatistics] gsd
		inner join [ob].[DimOBGlobalStatisticsPlan] gp 
			on gsd.OBGlobalStatisticsPlanID = gp.OBGlobalStatisticsPlanID
		inner join [clientob].[FactGlobalStatisticsDeptMapping] dm 
			on dm.OBGlobalStatisticID=gsd.OBGlobalStatisticID
		inner join [ob].[DimOBGlobalStatistics] gs 
			on gs.OBGlobalStatisticID=gsd.OBGlobalStatisticID
		inner join [ob].[viewDimDepartmentalBudget] db 
			on db.DepartmentID=dm.DepartmentID and db.EntityID = gp.EntityID
		inner join [fw].[DimDataType] dt 
			on dt.GlobalID='Output'
	where 
		dm.IsDeleted=0
	group by
		DepartmentalBudgetID,
		gp.OBGlobalStatisticsPlanID,
		dm.DepartmentID,
		gs.AccountID,
		dt.DataTypeID,
		TimeClassID,
		FiscalYearID,
		UnitTypeID,
		YTDAllocation,
		Allocation

UNION ALL
-----------------------------------------------------
------Department Statistics Budgeted Globally--------
-----------------------------------------------------
	select
		'Department' as Type,
		DepartmentalBudgetID,
		gp.OBGlobalStatisticsPlanID,
		gs.DepartmentID,
		gs.AccountID,
		dt.DataTypeID,
		TimeClassID,
		FiscalYearID,
		UnitTypeID,
		0 as YTDAllocation,
		0 as Allocation,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12
	from [clientob].[FactGlobalStatistics] gsd
		inner join [ob].[DimOBGlobalStatisticsPlan] gp 
			on gsd.OBGlobalStatisticsPlanID = gp.OBGlobalStatisticsPlanID
		inner join [ob].[DimOBGlobalStatistics] gs 
			on gs.OBGlobalStatisticID=gsd.OBGlobalStatisticID
		inner join [ob].[viewDimDepartmentalBudget] db 
			on db.DepartmentID=gs.DepartmentID
		inner join [fw].[DimDataType] dt 
			on dt.GlobalID='Output'
	where 1=1
		and gs.DepartmentID<>0
		and not exists 
			(
				select 1 
				from [clientob].[FactGlobalStatisticsDeptMapping] dm
					inner join [ob].[DimOBGlobalStatistics] gsm 
						on dm.OBGlobalStatisticID = gsm.OBGlobalStatisticID
				where 1=1
					and db.DepartmentID = dm.DepartmentID 
					and gsm.AccountID = gs.AccountID
					and dm.IsDeleted=0
			)
GO


---------------------------------------------

-- ob.viewReportGLDetail
CREATE VIEW ob.viewReportGLDetail AS

SELECT
	B.DepartmentalBudgetID,
	F.AccountID,
	F.ComponentID,
	F.ProjectID,
	F.FiscalMonthID,
	F.FiscalYearID,
	F.ClientCapitalID,
	F.ClientComponentID,
	F.ClientDate,
	F.Amount,
	F.ItemDescription,
	F.JournalNumber,
	F.JournalLineNumber,
	F.CustomText1,
	F.CustomText2,
	F.CustomText3,
	F.CustomText4,
	F.CustomText5,
	F.CustomDate1,
	F.CustomDate2,
	F.CustomNumeric1,
	F.CustomNumeric2,
	F.AccountID as AcctID,
	B.DepartmentalBudgetID as BudgID
FROM [int].[FactGLDetail] F
INNER JOIN [ob].[DimDepartmentalBudget] B ON B.DepartmentID = F.DepartmentID
WHERE IsDeleted=0
GO


---------------------------------------------

-- ob.viewReportGlobalStatisticsExceptionsSummary
Create view ob.viewReportGlobalStatisticsExceptionsSummary as
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Summarized OB Global Stat exceptions for dashboard
** Last Modified: 2015-01-09
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/

select 
e.OBExceptionsID,
sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open],
sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged
from [ob].[FactGlobalStatisticExceptions] e
group by e.OBExceptionsID
GO


---------------------------------------------

-- ob.viewReportPlanExpansion
CREATE VIEW [ob].[viewReportPlanExpansion]
AS
select 
	vp.PlanTypeName AS plantypename, 
	vp.planguid,
	fi.*,
	sd.MemberName,
	sd.DimensionName
from clientob.viewscorefillins AS fi 
	LEFT OUTER JOIN dbo.viewPlans AS vp ON fi.ModelGUID = vp.planguid
	left join [data].[viewScoreDimensionMember] sd on sd.MemberGUID=fi.PlaceholderSectionMemberGUID
where plantypeguid='05512126-3eb6-4da4-af6e-bc2bc2724b8b'
GO


---------------------------------------------

-- ob.viewReportReimbursementExceptionsSummary
Create view ob.viewReportReimbursementExceptionsSummary as
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Summarized OB Reimbursement exceptions for dashboard
** Last Modified: 2015-01-09
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/

select 
e.OBExceptionsID,
sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open],
sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged
from [ob].[FactReimbursementExceptions] e
group by e.OBExceptionsID
GO


---------------------------------------------

-- ob.viewReportSecurityDetail
--insert into DataView values(NEWID(), 'OB Duplicate Fill-Ins', 'dataob.viewReportDupeFillIns', dbo.ZeroGUID(), 0, '', dbo.ZeroGUID(), '')

CREATE view [ob].[viewReportSecurityDetail]
as
	select 
		S.* 
	from 
		fw.viewReportSecurityDetail S
		inner join  UserRole UR on UR.Name = S.USERROLE
	where
		UR.Category = 'OB'
GO


---------------------------------------------

-- ob.viewReportServiceLineExceptionsSummary
Create view ob.viewReportServiceLineExceptionsSummary as
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Summarized OB Service Line exceptions for dashboard
** Last Modified: 2015-01-09
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/

select 
e.OBExceptionsID,
sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open],
sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged
from [ob].[FactServiceLineExceptions] e
group by e.OBExceptionsID
GO


---------------------------------------------

-- ob.viewReportStaffingSnapshotData
/************************************************************
** Author: Joel Gerber
** Create Date: 2014-03-21
** Description: Reporting Staffing Data View for All OB Snapshot Reports
** Last Modified: 2014-03-21
** GM Release: NA (Customization)
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**
*************************************************************/

CREATE view [ob].[viewReportStaffingSnapshotData] as

select 
	data.DepartmentalBudgetID,
	EmployeeID,
	JobCodeID,
	PayCodeGroupID,
	PayCodeID,
	FiscalYearID,
	TimeClassID,
	UnitTypeID,
	DataTypeID,
	OBSnapshotID,
	Month01,
	Month02,
	Month03,
	Month04,
	Month05,
	Month06,
	Month07,
	Month08,
	Month09,
	Month10,
	Month11,
	Month12,
	data.MonthsLoaded,
	YTD,
	Yearly,
	Total
from
	[ob].[FactStaffingPCSnapshot] data
GO


---------------------------------------------

-- ob.viewReportStaffingtoGLAccount
CREATE view [ob].[viewReportStaffingtoGLAccount] as
	select * from ob.viewReportStaffingtoGLAccount_BothUnique
GO


---------------------------------------------

-- ob.viewReportStaffingtoGLAccount_BothOverride
CREATE view [ob].[viewReportStaffingtoGLAccount_BothOverride] as
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut3.UnitTypeID,
		data.DataTypeID,
		data.Month01/whpm.Month01 as Month01,
		data.Month02/whpm.Month02 as Month02,
		data.Month03/whpm.Month03 as Month03,
		data.Month04/whpm.Month04 as Month04,
		data.Month05/whpm.Month05 as Month05,
		data.Month06/whpm.Month06 as Month06,
		data.Month07/whpm.Month07 as Month07,
		data.Month08/whpm.Month08 as Month08,
		data.Month09/whpm.Month09 as Month09,
		data.Month10/whpm.Month10 as Month10,
		data.Month11/whpm.Month11 as Month11,
		data.Month12/whpm.Month12 as Month12,
		data.YTD/(case
		when data.MonthsLoaded = 1 then whpm.Month01
		when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02
		when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03
		when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04
		when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05
		when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06
		when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07
		when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08
		when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09
		when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10
		when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11
		else whpm.MonthYearly end) as YTD,
		data.Total/whpm.MonthYearly as Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut3.UnitTypeID,
		data.DataTypeID,
		data.Month01/whpm.Month01 as Month01,
		data.Month02/whpm.Month02 as Month02,
		data.Month03/whpm.Month03 as Month03,
		data.Month04/whpm.Month04 as Month04,
		data.Month05/whpm.Month05 as Month05,
		data.Month06/whpm.Month06 as Month06,
		data.Month07/whpm.Month07 as Month07,
		data.Month08/whpm.Month08 as Month08,
		data.Month09/whpm.Month09 as Month09,
		data.Month10/whpm.Month10 as Month10,
		data.Month11/whpm.Month11 as Month11,
		data.Month12/whpm.Month12 as Month12,
		data.YTD/(case
		when data.MonthsLoaded = 1 then whpm.Month01
		when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02
		when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03
		when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04
		when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05
		when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06
		when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07
		when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08
		when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09
		when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10
		when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11
		else whpm.MonthYearly end) as YTD,
		data.Total/whpm.MonthYearly as Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and ut2.UnitTypeID = pax.UnitTypeID
		inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
		and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and ut2.UnitTypeID=pax2.UnitTypeID)
	union all
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut2.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours')  and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut2.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and ut2.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours')  and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
		and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and ut2.UnitTypeID=pax2.UnitTypeID)
	union all
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		data.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID
	where 
		ut1.Name = 'Dollars'
	union all
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		data.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and data.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID
	where 
		ut1.Name = 'Dollars'
		and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and data.UnitTypeID=pax2.UnitTypeID)
GO


---------------------------------------------

-- ob.viewReportStaffingtoGLAccount_BothUnique
CREATE view [ob].[viewReportStaffingtoGLAccount_BothUnique] as
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut3.UnitTypeID,
		data.DataTypeID,
		data.Month01/whpm.Month01 as Month01,
		data.Month02/whpm.Month02 as Month02,
		data.Month03/whpm.Month03 as Month03,
		data.Month04/whpm.Month04 as Month04,
		data.Month05/whpm.Month05 as Month05,
		data.Month06/whpm.Month06 as Month06,
		data.Month07/whpm.Month07 as Month07,
		data.Month08/whpm.Month08 as Month08,
		data.Month09/whpm.Month09 as Month09,
		data.Month10/whpm.Month10 as Month10,
		data.Month11/whpm.Month11 as Month11,
		data.Month12/whpm.Month12 as Month12,
		data.YTD/(case
		when data.MonthsLoaded = 1 then whpm.Month01
		when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02
		when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03
		when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04
		when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05
		when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06
		when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07
		when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08
		when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09
		when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10
		when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11
		else whpm.MonthYearly end) as YTD,
		data.Total/whpm.MonthYearly as Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut2.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours')  and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		data.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID
	where 
		ut1.Name = 'Dollars'
GO


---------------------------------------------

-- ob.viewReportStaffingtoGLAccount_EachJobCode
CREATE view [ob].[viewReportStaffingtoGLAccount_EachJobCode] as
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut3.UnitTypeID,
		data.DataTypeID,
		data.Month01/whpm.Month01 as Month01,
		data.Month02/whpm.Month02 as Month02,
		data.Month03/whpm.Month03 as Month03,
		data.Month04/whpm.Month04 as Month04,
		data.Month05/whpm.Month05 as Month05,
		data.Month06/whpm.Month06 as Month06,
		data.Month07/whpm.Month07 as Month07,
		data.Month08/whpm.Month08 as Month08,
		data.Month09/whpm.Month09 as Month09,
		data.Month10/whpm.Month10 as Month10,
		data.Month11/whpm.Month11 as Month11,
		data.Month12/whpm.Month12 as Month12,
		data.YTD/(case
		when data.MonthsLoaded = 1 then whpm.Month01
		when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02
		when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03
		when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04
		when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05
		when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06
		when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07
		when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08
		when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09
		when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10
		when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11
		else whpm.MonthYearly end) as YTD,
		data.Total/whpm.MonthYearly as Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs'
        inner join [fw].[DimJobCode] djc with (readuncommitted) on data.JobCodeID = djc.JobCodeID
        inner join [ob].[DimDepartmentalBudget] ddb with (readuncommitted) on data.DepartmentalBudgetID = ddb.DepartmentalBudgetID
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID = whpm.FiscalYearID 
        and case 
                when djc.WorkWeekOverrideID = -1 and ddb.EntityDefaultWorkWeekID = whpm.WorkWeekID then 1
                when djc.WorkWeekOverrideID != -1 and djc.WorkWeekOverrideID = whpm.WorkWeekID then 1
            else 0
            end = 1        
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID = data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut2.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours')  and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		data.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID
	where 
		ut1.Name = 'Dollars'
GO


---------------------------------------------

-- ob.viewReportStaffingtoGLAccount_EachPayCodeGroup
CREATE view [ob].[viewReportStaffingtoGLAccount_EachPayCodeGroup] as
	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut3.UnitTypeID,
		data.DataTypeID,
		data.Month01/whpm.Month01 as Month01,
		data.Month02/whpm.Month02 as Month02,
		data.Month03/whpm.Month03 as Month03,
		data.Month04/whpm.Month04 as Month04,
		data.Month05/whpm.Month05 as Month05,
		data.Month06/whpm.Month06 as Month06,
		data.Month07/whpm.Month07 as Month07,
		data.Month08/whpm.Month08 as Month08,
		data.Month09/whpm.Month09 as Month09,
		data.Month10/whpm.Month10 as Month10,
		data.Month11/whpm.Month11 as Month11,
		data.Month12/whpm.Month12 as Month12,
		data.YTD/(case
		when data.MonthsLoaded = 1 then whpm.Month01
		when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02
		when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03
		when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04
		when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05
		when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06
		when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07
		when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08
		when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09
		when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10
		when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11
		else whpm.MonthYearly end) as YTD,
		data.Total/whpm.MonthYearly as Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		ut2.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID
		inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours'
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and ut2.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID
	where 
		ut1.Name in('Non-Productive Hours', 'Productive Hours')  and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive
	union all

	select 
		data.DepartmentalBudgetID,
		pax.AccountID,
		data.JobCodeID,
		data.PayCodeGroupID,
		data.FiscalYearID,
		data.TimeClassID,
		data.UnitTypeID,
		data.DataTypeID,
		data.Month01 as Month01,
		data.Month02 as Month02,
		data.Month03 as Month03,
		data.Month04 as Month04,
		data.Month05 as Month05,
		data.Month06 as Month06,
		data.Month07 as Month07,
		data.Month08 as Month08,
		data.Month09 as Month09,
		data.Month10 as Month10,
		data.Month11 as Month11,
		data.Month12 as Month12,
		data.YTD,
		data.Total
	from
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.UnitTypeID = pax.UnitTypeID
		inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID
	where 
		ut1.Name = 'Dollars'
GO


---------------------------------------------

-- ob.viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue
/************************************************************
** Author: Bart Lewis
** Create Date: 4/22/2015
** Description: Budget Service Line Revenue Sampling View From Import Tables
** Last Modified: 4/22/2015
** GM Release: 2015.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

Create View [ob].[viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue] As

select 
	[DataTypeID]
	, [FiscalYearID]
	, [FiscalMonthID]
	, [ModelingServiceLineID]
	, [PayorID]
	, [PayorGroupID]
	, [OBForecastDetailID]
	, [OBServiceLinePlanID]
	, [TimeClassID]
	, [UnitTypeID]
	, [HistoryItemGUID]
	, [TransactionID]
	, ISNULL(Month01, 0) [Month01]
	, ISNULL(Month02, 0) [Month02]
	, ISNULL(Month03, 0) [Month03]
	, ISNULL(Month04, 0) [Month04]
	, ISNULL(Month05, 0) [Month05]
	, ISNULL(Month06, 0) [Month06]
	, ISNULL(Month07, 0) [Month07]
	, ISNULL(Month08, 0) [Month08]
	, ISNULL(Month09, 0) [Month09]
	, ISNULL(Month10, 0) [Month10]
	, ISNULL(Month11, 0) [Month11]
	, ISNULL(Month12, 0) [Month12]
	, ISNULL(Month00, 0) [Yearly]
	, (ISNULL(Month01, 0)
		+ISNULL(Month02, 0)
		+ISNULL(Month03, 0)
		+ISNULL(Month04, 0)
		+ISNULL(Month05, 0)
		+ISNULL(Month06, 0)
		+ISNULL(Month07, 0)
		+ISNULL(Month08, 0)
		+ISNULL(Month09, 0)
		+ISNULL(Month10, 0)
		+ISNULL(Month11, 0)
		+ISNULL(Month12, 0)
		+ISNULL(Month00, 0)) as [Total]
from
(
	SELECT 
		4 [DataTypeID]
		, c.[FiscalYearID]
		, c.[FiscalMonthID]
		, m.[ModelingServiceLineID]
		, p.[PayorID]
		, pg.[PayorGroupID]
		, ob.[OBForecastDetailID]
		, slp.[OBServiceLinePlanID]
		, c.[TimeClassID]
		, ob.[UnitTypeID]
		, c.[Value] as [Amount]		
		, fm.[MonthColumnName]
		, c.[HistoryItemGUID]
		, c.[TransactionID]
	FROM [int].[FactFinancialServiceLineRevenue] c
	inner join [fw].[DimModelingServiceLine] m on c.ServiceLineID=m.ServiceLineID and c.AgeCohortID=m.AgeCohortID and c.MedicalSurgicalID=m.MedicalSurgicalID and c.PatientClassID=m.PatientClassID
	inner join [fw].[DimForecastDetail] fd on c.ForecastDetailID=fd.ForecastDetailID
	inner join [ob].[DimOBForecastDetail] ob on ob.OBForecastDetailID=fd.OBForecastDetailID
	inner join [fw].[DimPayor] p on p.PayorID=c.PayorID
	inner join [fw].[DimPayorGroup] pg on c.PayorGroupID=pg.PayorGroupID
	inner join [fw].[DimEntity] e on c.EntityID=e.EntityID
	inner join [ob].[DimOBServiceLinePlan] slp on e.EntityID=slp.EntityID and slp.IsDeleted=0
	inner join [fw].[DimFiscalMonth] fm on c.FiscalMonthID=fm.FiscalMonthID
) as data
PIVOT
(
SUM(Amount) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])
) as pvt
GO


---------------------------------------------

-- ob.viewSystemCenterAccess
create view [ob].[viewSystemCenterAccess]
as
select
				s.SectionGUID,
				s.Name as SectionName, 
				c.CategoryGUID,
				c.Name as CategoryName,
				m.ModuleGUID,
				m.Name as ModuleName,
				ISNULL(p.ReadValue, 0) ReadValue,
				ISNULL(p.WriteValue, 0) WriteValue,
				ISNULL(p.PermissionGUID, '00000000-0000-0000-0000-000000000000') PermissionGUID
				from
		SystemCenterSection s 
		inner join SystemCenterCategory c on s.CategoryGUID = c.CategoryGUID
		inner join SystemCenterModule m on c.ModuleGUID = m.ModuleGUID
		left join S3SimplePermission p on s.SectionGUID = p.LootID and p.IdentityGUID = (select UserGroupGUID from UserGroup where Name = 'ob - local administrator')
		where
       m.Name in('General', 'Operating Budgeting')
	   and s.Name in('Detailed Adjustment Import', 'Budget Import', 'Role Assignments', 'Manage Global Assumptions', 'Budget-Level Assumptions', 'System-Generated Statistics')	
	   and c.IsMaintenanceMode = 1
GO


---------------------------------------------

-- ob.viewSystemSetting
create view ob.viewSystemSetting
as
	select * from ob.SystemSetting 
	where 
		Name not like 'AP%' 
		and Name not like '%ABB%' 
		and Name not like '%APE%' 
		and Description not like '%APE%'
GO


---------------------------------------------

-- ob.viewValidDataTypeTimeClassFiscalYearCombos
CREATE view [ob].[viewValidDataTypeTimeClassFiscalYearCombos] 
as
	select 
		DataTypeID		= dt.DataTypeID,
		FiscalYearID	= fy.FiscalYearID,
		TimeClassID		= tc.TimeClassID,
		IsCY			= case fy.FiscalYearID
								when dbs.Setting then 1
								else 0
							end
	from [dbo].[DBSetting] dbs with (readuncommitted)
		cross join [fw].[DimDataType] dt with (readuncommitted)
		cross join [fw].[DimFiscalYear] fy with (readuncommitted)
		cross join [fw].[DimTimeClass] tc with (readuncommitted)
	where 1=1
		and dbs.Name = 'OB_Current_Year'
		and 
		(
				(dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting-1 and tc.TimeClassID = 1)	--PY Actual
			or
				(dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 1)	--CY Actual
			or
				(dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 2)	--CY Budget
			or
				(dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 12)	--CY Projection
			or
				(dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting+1 and tc.TimeClassID = 18)	--BY Baseline
			or
				(dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting+1 and tc.TimeClassID = 2)	--BY Budget
		)
GO


---------------------------------------------

---------------------------------------------
--  PROCEDURES
---------------------------------------------

-- ob.procAllocationSampleAll
create proc [ob].[procAllocationSampleAll]
	@isDebugOnly bit = 0
as
/**********************************************************************************
** Author: Corey Becker (Donatello)
** Create Date: 2016-02-11
** Description: Loops through allocation sampling by execution order
** Last Modified: 2016-02-11
** GM Release: 2016.2
**********************************************************************************
** Change History
**********************************************************************************
**	CID		Date	Author	WI		Description
**	
**********************************************************************************/

------------------------------------------------------------------------------------------------
------------------------------- Variable declarations ------------------------------------------
------------------------------------------------------------------------------------------------
declare @sql as nvarchar(max) = ''

------------------------------------------------------------------------------------------------
----------------- Delete all existing allocation data for affected departments -----------------
------------------------------------------------------------------------------------------------
	if @isDebugOnly=1
		begin
			set @sql = 'Proc will delete all existing allocation data for affected departments. Preview using this select statement:

select fct.*
from [clientob].[FactAccount] fct 
	inner join [data].[ScoreFillin_Account] sf 
		on fct.AccountID=sf.AccountID
	inner join [ob].[DimAccountPH] ph
		on sf.AccountPHID=ph.AccountPHID
	inner join [ob].[viewAllocationValues] av
		on fct.DepartmentalBudgetID=av.DepartmentalBudgetTargetID
where 1=1
	and ph.Name like ''%Allocated''
	and fct.TimeClassID=2
	and fct.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name=''OB_Current_Year'')
	'
			print(@sql)
		end
	else
		begin
			delete fct
			from [clientob].[FactAccount] fct 
				inner join [data].[ScoreFillin_Account] sf 
					on fct.AccountID=sf.AccountID
				inner join [ob].[DimAccountPH] ph
					on sf.AccountPHID=ph.AccountPHID
				inner join [ob].[viewAllocationValues] av
					on fct.DepartmentalBudgetID=av.DepartmentalBudgetTargetID
			where 1=1
				and ph.Name like '%Allocated'
				and fct.TimeClassID=2
				and fct.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year')
		end

------------------------------------------------------------------------------------------------
------------------- xxx ---------------------
------------------------------------------------------------------------------------------------
declare @currentExecOrder smallint

if @isDebugOnly=1
	begin
		print ('Procedure will then run the following: ')

		declare allocationCursor CURSOR FAST_FORWARD FOR
			select distinct dm.ExecutionOrder
			from [ob].[viewDimOBAllocation] dm
			where OBAllocationID<>0

		open allocationCursor;

		FETCH NEXT FROM allocationCursor into @currentExecOrder
		WHILE (@@FETCH_STATUS = 0) 
			BEGIN
				set @sql = 'exec [clientob].[procAllocationSample] @execOrder = '+cast(@currentExecOrder as nvarchar(8))
				print(@sql)
				FETCH NEXT FROM allocationCursor into @currentExecOrder
			END
		close allocationCursor;
		deallocate allocationCursor;
	end
else
	begin
		declare allocationCursor CURSOR FAST_FORWARD FOR
			select distinct dm.ExecutionOrder
			from [ob].[viewDimOBAllocation] dm
			where OBAllocationID<>0

		open allocationCursor;

		FETCH NEXT FROM allocationCursor into @currentExecOrder
		WHILE (@@FETCH_STATUS = 0) 
			BEGIN
				set @sql = 'exec [clientob].[procAllocationSample] @execOrder = '+cast(@currentExecOrder as nvarchar(8))
				exec(@sql)
				FETCH NEXT FROM allocationCursor into @currentExecOrder
			END
		close allocationCursor;
		deallocate allocationCursor;
	end




------------------------------------------------------------------------------------------------
----------------------------------- Invalidate model cache -------------------------------------
------------------------------------------------------------------------------------------------
if @isDebugOnly=1
	begin
		print('Then model caches are invalidated, if present')
	end
else
	begin
		if exists 
			(
				select 1
				from [dbo].[XPlan]
				where 1=1
					and PlanTypeGUID='05512126-3EB6-4DA4-AF6E-BC2BC2724B8B'
					and ModelTemplateGUID<>'00000000-0000-0000-0000-000000000000'
					and IsDeletedPlan=0 
					and IsModelWorkbookCached=1
			)
			begin
				exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] 
					@planTypeGUID = '05512126-3EB6-4DA4-AF6E-BC2BC2724B8B',
					@source = 'procFactAllocationSample'
			end
	end

------------------------------------------------------------------------------------------------
----------------------------------------- Log Script -------------------------------------------
------------------------------------------------------------------------------------------------
if @isDebugOnly=1
	begin
		print('Finally, the script is logged')
	end
else
	begin
		declare @higuid2 uniqueidentifier
		exec [dbo].[procLogScript] 
			@desc =  'Allocation Sample All Complete',
			@higuid = @higuid2 output
	end

return
GO


---------------------------------------------

-- ob.procBudgetStampOffInsert
/************************************************************************************************************************
** Author: Mike Schmitz
** Create Date: 2014-09-15
** Description: Populates Budget Data into the Budget Stamp-Off tables
** Last Modified: 2014-09-15
** GM Release: 2014.4
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI		Description
**	1		8-24-2015	bjl				comment out incorrect value filters
*************************************************************************************************************************/
CREATE proc [ob].[procBudgetStampOffInsert] as

/************** Logging *********************************************************/
declare @higuid uniqueidentifier
exec procLogScript 'Operating Budget Stamp-Off Insert' , @higuid output
print 'Beginning insert, historyitemguid: ' + cast(@higuid as varchar(36))

/************** Insert **********************************************************/
declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year')

--FactAccount
truncate table [clientob].[FactAccountBudgetStampOff]

insert into [clientob].[FactAccountBudgetStampOff] (DepartmentalBudgetID, AccountID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, Yearly,	HistoryItemGUID)

	select
		DepartmentalBudgetID, 
		AccountID, 
		FiscalYearID, 
		TimeClassID, 
		UnitTypeID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactAccount]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		DepartmentalBudgetID,
		AccountID, 
		FiscalYearID, 
		TimeClassID, 
		UnitTypeID
		
--FactGlobalStatistics
truncate table [clientob].[FactGlobalStatisticsBudgetStampOff]

insert into [clientob].[FactGlobalStatisticsBudgetStampOff] (TimeClassID,FiscalYearID,UnitTypeID,OBGlobalStatisticID,OBGlobalStatisticsPlanID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		TimeClassID, 
		FiscalYearID, 
		UnitTypeID, 
		OBGlobalStatisticID,
		OBGlobalStatisticsPlanID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactGlobalStatistics]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		TimeClassID, 
		FiscalYearID, 
		UnitTypeID, 
		OBGlobalStatisticID,
		OBGlobalStatisticsPlanID

--FactReimbursement
truncate table [clientob].[FactReimbursementBudgetStampOff]

insert into [clientob].[FactReimbursementBudgetStampOff] (FiscalYearID,OBForecastDetailID,OBReimbursementPlanID,PatientReimbursementGroupID,PayorID,PayorGroupID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		FiscalYearID,
		OBForecastDetailID,
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		PayorID,
		PayorGroupID,
		TimeClassID,
		UnitTypeID,		
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactReimbursement]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		FiscalYearID,
		OBForecastDetailID,
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		PayorID,
		PayorGroupID,
		TimeClassID,
		UnitTypeID
		
--FactReimbursementAccount
truncate table [clientob].[FactReimbursementAccountBudgetStampOff]

insert into [clientob].[FactReimbursementAccountBudgetStampOff] (AccountID,FiscalYearID,OBReimbursementPlanID,PatientReimbursementGroupID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		AccountID,
		FiscalYearID,
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		TimeClassID,
		UnitTypeID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactReimbursementAccount]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		AccountID,
		FiscalYearID,
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		TimeClassID,
		UnitTypeID	

--FactStaffingPC
truncate table [clientob].[FactStaffingPCBudgetStampOff]

insert into [clientob].[FactStaffingPCBudgetStampOff] (EmployeeID,FiscalYearID,JobCodeID,DepartmentalBudgetID,TimeClassID,PayCodeGroupID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		EmployeeID,
		FiscalYearID, 
		JobCodeID,
		DepartmentalBudgetID, 
		TimeClassID,
		PayCodeGroupID,
		UnitTypeID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactStaffingPC]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		EmployeeID,
		FiscalYearID, 
		JobCodeID,
		DepartmentalBudgetID, 
		TimeClassID,
		PayCodeGroupID,
		UnitTypeID

--FactCDM
truncate table [clientob].[FactCDMBudgetStampOff]

insert into [clientob].[FactCDMBudgetStampOff] (ChargeCodeID,FiscalYearID,DepartmentalBudgetID,OBForecastDetailID,PatientClassID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		ChargeCodeID,
		FiscalYearID, 
		DepartmentalBudgetID, 
		OBForecastDetailID,
		PatientClassID,
		TimeClassID,
		UnitTypeID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactCDM]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		ChargeCodeID,
		FiscalYearID, 
		DepartmentalBudgetID, 
		OBForecastDetailID,
		PatientClassID,
		TimeClassID,
		UnitTypeID

--FactServiceLine
truncate table [clientob].[FactServiceLineBudgetStampOff]

insert into [clientob].[FactServiceLineBudgetStampOff] (FiscalYearID,ModelingServiceLineID,TimeClassID,UnitTypeID,OBForecastDetailID,OBServiceLinePlanID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		FiscalYearID, 
		ModelingServiceLineID,
		TimeClassID,
		UnitTypeID,
		OBForecastDetailID,
		OBServiceLinePlanID,		
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactServiceLine]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		FiscalYearID, 
		ModelingServiceLineID,
		TimeClassID,
		UnitTypeID,
		OBForecastDetailID,
		OBServiceLinePlanID

--FactProvider
truncate table [clientob].[FactProviderBudgetStampOff]

insert into [clientob].[FactProviderBudgetStampOff] (FiscalYearID,UnitTypeID,DepartmentalBudgetID,TimeClassID,ProviderID,OBForecastDetailID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID)

	select
		FiscalYearID, 
		UnitTypeID,
		DepartmentalBudgetID,
		TimeClassID,
		ProviderID,
		OBForecastDetailID,
		sum(Month01),
		sum(Month02),
		sum(Month03),
		sum(Month04),
		sum(Month05),
		sum(Month06),
		sum(Month07),
		sum(Month08),
		sum(Month09),
		sum(Month10),
		sum(Month11),
		sum(Month12),
		sum(Yearly),
		@higuid
	from 
		[clientob].[FactProvider]
	where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID
--CID 1 Begin
--	and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0)
--CID 1 End
	group by 
		FiscalYearID, 
		UnitTypeID,
		DepartmentalBudgetID,
		TimeClassID,
		ProviderID,
		OBForecastDetailID		
		
RETURN
GO


---------------------------------------------

-- ob.procBudgetUploadFactAccountSample
CREATE procedure ob.procBudgetUploadFactAccountSample
	@historyItemGUID uniqueidentifier
as
	delete fa
	from 
		clientob.FactAccount fa
	where
		fa.DataTypeID = 3	--output
		and fa.TimeClassID != 1	--actual
		and exists(
			select 1 
			from
				clientob.FactAccountNonReporting nr
			where
				nr.HistoryItemGUID = @historyItemGUID
				and nr.AccountID = fa.AccountID
				and nr.FiscalYearID = fa.FiscalYearID
				and nr.DepartmentalBudgetID = fa.DepartmentalBudgetID
				and nr.TimeClassID = fa.TimeClassID
				and nr.UnitTypeID = fa.UnitTypeID
		);

	insert into clientob.FactAccount (AccountID, DataTypeID, FiscalYearID, DepartmentalBudgetID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, Yearly, MonthsLoaded, IsDeleted, TransactionID, HistoryItemGUID)
	select fa.AccountID, 3 as DataTypeID, fa.FiscalYearID, fa.DepartmentalBudgetID, fa.TimeClassID, fa.UnitTypeID, fa.Month01, fa.Month02, fa.Month03, fa.Month04, fa.Month05, fa.Month06, fa.Month07, fa.Month08, fa.Month09, fa.Month10, fa.Month11, fa.Month12, fa.Yearly, fa.MonthsLoaded, fa.IsDeleted, fa.TransactionID, fa.HistoryItemGUID
	from clientob.FactAccountNonReporting fa
	where fa.HistoryItemGUID = @historyItemGUID and fa.DataTypeID = 4 and fa.TimeClassID != 1;
GO


---------------------------------------------

-- ob.procCAPOperationsToOBSubTable_Transfer
CREATE proc [ob].[procCAPOperationsToOBSubTable_Transfer]
/****************************************************************************************************
** Author: cbb
** Create Date: 2017.02.14
** Description: Transfer capital revenue and expenses to department budget
** Last Modified: 2017.02.14
** GM Release: 2017.2.0
****************************************************************************************************
** Change History
****************************************************************************************************
** CID	Date		Author	WI		Description
** 
****************************************************************************************************/
as
	begin
--------------------------------------------------------------------------------------------------
-- Variables
--------------------------------------------------------------------------------------------------
	declare @higuid uniqueidentifier
	
	declare @currYear int
	select @currYear = Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year'

	declare @planRefreshList as nvarchar(max) = ''

--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	exec procLogScript 'Transfer project pro forma financials to OB sub-table composite' , @higuid output
	--print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Create temp table
--------------------------------------------------------------------------------------------------
	create table #dataagg
		(
			[TimeClassID] tinyint,
			[FiscalYearID] smallint,
			[DepartmentalBudgetID] int,
			[AccountID] int,
			[UnitTypeID] tinyint,
			[AssumptionID] int,
			[Month01] decimal(19,4),
			[Month02] decimal(19,4),
			[Month03] decimal(19,4),
			[Month04] decimal(19,4),
			[Month05] decimal(19,4),
			[Month06] decimal(19,4),
			[Month07] decimal(19,4),
			[Month08] decimal(19,4),
			[Month09] decimal(19,4),
			[Month10] decimal(19,4),
			[Month11] decimal(19,4),
			[Month12] decimal(19,4),
			[Yearly] decimal(19,4),
			[Total] decimal(31,4),
			[Comment] nvarchar(4000),
			[IsDeleted] bit,
			[HistoryItemGUID] uniqueidentifier,
			[TransactionID] int,
			[AdjustmentCategoryID] int
		)

--------------------------------------------------------------------------------------------------
-- Populate temp table
--------------------------------------------------------------------------------------------------
	insert into #dataagg
		(
			[TimeClassID],
			[FiscalYearID],
			[DepartmentalBudgetID],
			[AccountID],
			[UnitTypeID],
			[AssumptionID],
			[Month01],
			[Month02],
			[Month03],
			[Month04],
			[Month05],
			[Month06],
			[Month07],
			[Month08],
			[Month09],
			[Month10],
			[Month11],
			[Month12],
			[Yearly],
			[Comment],
			[HistoryItemGUID],
			[TransactionID],
			[AdjustmentCategoryID]
		)
	select 
			[TimeClassID]			= case fct.FiscalYearID
											when @currYear then 12
											else 2
										end,
			[FiscalYearID]			= fct.FiscalYearID,
			[DepartmentalBudgetID]	= ddb.DepartmentalBudgetID,
			[AccountID]				= fd.AccountID,
			[UnitTypeID]			= fct.UnitTypeID,
			[AssumptionID]			= 18,
			[Month01]				= sum(fct.Month01),
			[Month02]				= sum(fct.Month02),
			[Month03]				= sum(fct.Month03),
			[Month04]				= sum(fct.Month04),
			[Month05]				= sum(fct.Month05),
			[Month06]				= sum(fct.Month06),
			[Month07]				= sum(fct.Month07),
			[Month08]				= sum(fct.Month08),
			[Month09]				= sum(fct.Month09),
			[Month10]				= sum(fct.Month10),
			[Month11]				= sum(fct.Month11),
			[Month12]				= sum(fct.Month12),
			[Yearly]				= sum(fct.Yearly),
			[Comment]				= 'Transfer from Capital - Model: ' + dp.Name + ' - Forecast Line: ' + fd.Name,
			[HistoryItemGUID]		= @higuid,
			[TransactionID]			= -99,
			[AdjustmentCategoryID]	= 0
	from [clientcap].[FactCAPProjectOperationsMonthly] fct
		inner join [cap].[viewDimProject] dp
			on fct.ProjectID = dp.ProjectID
		inner join [cap].[viewDimForecastDetail] fd
			on fct.CAPForecastDetailID=fd.CAPForecastDetailID
		inner join [ob].[viewDimDepartmentalBudget] ddb
			on dp.DepartmentID = ddb.DepartmentID
	where 1=1
		and fct.IsDeleted = 0
		and dp.IncludeinOB = 1
		and fd.AccountID > 0
		and fct.UnitTypeID = 34
		and fct.FiscalYearID in (@currYear, @currYear+1)
	group by
		fct.FiscalYearID,
		ddb.DepartmentalBudgetID,
		fd.AccountID,
		dp.Name,
		fd.Name,
		fct.UnitTypeID

--------------------------------------------------------------------------------------------------
-- Populate temp table - Yearly capital structure
--------------------------------------------------------------------------------------------------
	insert into #dataagg
		(
			[TimeClassID],
			[FiscalYearID],
			[DepartmentalBudgetID],
			[AccountID],
			[UnitTypeID],
			[AssumptionID],
			[Month01],
			[Month02],
			[Month03],
			[Month04],
			[Month05],
			[Month06],
			[Month07],
			[Month08],
			[Month09],
			[Month10],
			[Month11],
			[Month12],
			[Yearly],
			[Comment],
			[HistoryItemGUID],
			[TransactionID],
			[AdjustmentCategoryID]
		)
	select 
			[TimeClassID]			= case fct.FiscalYearID
											when @currYear then 12
											else 2
										end,
			[FiscalYearID]			= fct.FiscalYearID,
			[DepartmentalBudgetID]	= ddb.DepartmentalBudgetID,
			[AccountID]				= fd.AccountID,
			[UnitTypeID]			= fct.UnitTypeID,
			[AssumptionID]			= 18,
			[Month01]				= 0,
			[Month02]				= 0,
			[Month03]				= 0,
			[Month04]				= 0,
			[Month05]				= 0,
			[Month06]				= 0,
			[Month07]				= 0,
			[Month08]				= 0,
			[Month09]				= 0,
			[Month10]				= 0,
			[Month11]				= 0,
			[Month12]				= 0,
			[Yearly]				= sum(fct.Amount),
			[Comment]				= 'Transfer from Capital - Model: ' + dp.Name + ' - Forecast Line: ' + fd.Name,
			[HistoryItemGUID]		= @higuid,
			[TransactionID]			= -99,
			[AdjustmentCategoryID]	= 0
	from [clientcap].[FactProjectOperations] fct
		inner join [cap].[viewDimProject] dp
			on fct.ProjectID = dp.ProjectID
		inner join [cap].[viewDimForecastDetail] fd
			on fct.CAPForecastDetailID=fd.CAPForecastDetailID
		inner join [ob].[viewDimDepartmentalBudget] ddb
			on dp.DepartmentID = ddb.DepartmentID
	where 1=1
		and fct.IsDeleted = 0
		and dp.IncludeinOB = 1
		and fd.AccountID > 0
		and fct.UnitTypeID = 34
		and fct.FiscalYearID in (@currYear, @currYear+1)
	group by
		fct.FiscalYearID,
		ddb.DepartmentalBudgetID,
		fd.AccountID,
		dp.Name,
		fd.Name,
		fct.UnitTypeID

--------------------------------------------------------------------------------------------------
-- Create dept temp table
--------------------------------------------------------------------------------------------------
	select tmp.[DepartmentalBudgetID], ddb.MemberGUID, 0 as IsRefreshNeeded
	into #depts 
	from #dataagg tmp
		inner join [ob].[DimDepartmentalBudget] ddb
			on tmp.DepartmentalBudgetID = ddb.DepartmentalBudgetID
		
--------------------------------------------------------------------------------------------------
-- Delete sub-table records no longer present in capital projects
--------------------------------------------------------------------------------------------------
	update dept
	set IsRefreshNeeded=1
	from #depts dept
		inner join [clientob].[FactAccountSubtableVar] fctv
			on fctv.DepartmentalBudgetID = dept.DepartmentalBudgetID
		left join #dataagg tmp
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and tmp.TimeClassID is null
		and 
			(
				(fctv.FiscalYearID = @currYear and fctv.TimeClassID = 12)
				or 
				(fctv.FiscalYearID = @currYear+1 and fctv.TimeClassID = 2)
			)
		and fctv.TransactionID = -99
		and fctv.Comment like 'Transfer from Capital - Model: %'

	delete fctv
	from [clientob].[FactAccountSubtableVar] fctv
		left join #dataagg tmp
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and tmp.TimeClassID is null
		and 
			(
				(fctv.FiscalYearID = @currYear and fctv.TimeClassID = 12)
				or 
				(fctv.FiscalYearID = @currYear+1 and fctv.TimeClassID = 2)
			)
		and fctv.TransactionID = -99
		and fctv.Comment like 'Transfer from Capital - Model: %'

--------------------------------------------------------------------------------------------------
-- Update existing sub-table records
--------------------------------------------------------------------------------------------------
	update dept
	set IsRefreshNeeded=1
	from #depts dept
		inner join [clientob].[FactAccountSubtableVar] fctv
			on dept.DepartmentalBudgetID=fctv.DepartmentalBudgetID
		inner join #dataagg tmp
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and
			(
				fctv.Month01<>tmp.Month01
				or fctv.Month02<>tmp.Month02
				or fctv.Month03<>tmp.Month03
				or fctv.Month04<>tmp.Month04
				or fctv.Month05<>tmp.Month05
				or fctv.Month06<>tmp.Month06
				or fctv.Month07<>tmp.Month07
				or fctv.Month08<>tmp.Month08
				or fctv.Month09<>tmp.Month09
				or fctv.Month10<>tmp.Month10
				or fctv.Month11<>tmp.Month11
				or fctv.Month12<>tmp.Month12
				or fctv.Yearly<>tmp.Yearly
			)

	update fctv
	set 
		fctv.Month01=tmp.Month01,
		fctv.Month02=tmp.Month02,
		fctv.Month03=tmp.Month03,
		fctv.Month04=tmp.Month04,
		fctv.Month05=tmp.Month05,
		fctv.Month06=tmp.Month06,
		fctv.Month07=tmp.Month07,
		fctv.Month08=tmp.Month08,
		fctv.Month09=tmp.Month09,
		fctv.Month10=tmp.Month10,
		fctv.Month11=tmp.Month11,
		fctv.Month12=tmp.Month12,
		fctv.Yearly=tmp.Yearly,
		fctv.HistoryItemGUID = @higuid
	from [clientob].[FactAccountSubtableVar] fctv
		inner join #dataagg tmp
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and
			(
				fctv.Month01<>tmp.Month01
				or fctv.Month02<>tmp.Month02
				or fctv.Month03<>tmp.Month03
				or fctv.Month04<>tmp.Month04
				or fctv.Month05<>tmp.Month05
				or fctv.Month06<>tmp.Month06
				or fctv.Month07<>tmp.Month07
				or fctv.Month08<>tmp.Month08
				or fctv.Month09<>tmp.Month09
				or fctv.Month10<>tmp.Month10
				or fctv.Month11<>tmp.Month11
				or fctv.Month12<>tmp.Month12
				or fctv.Yearly<>tmp.Yearly
			)


--------------------------------------------------------------------------------------------------
-- Update existing sub-table records
--------------------------------------------------------------------------------------------------
	update dept
	set IsRefreshNeeded=1
	from #depts dept
		inner join #dataagg tmp
			on dept.DepartmentalBudgetID=tmp.DepartmentalBudgetID
		left join [clientob].[FactAccountSubtableVar] fctv
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and fctv.TimeClassID is null
			
			
	insert into [clientob].[FactAccountSubtableVar]
		(
			[TimeClassID],
			[FiscalYearID],
			[DepartmentalBudgetID],
			[AccountID],
			[UnitTypeID],
			[AssumptionID],
			[Month01],
			[Month02],
			[Month03],
			[Month04],
			[Month05],
			[Month06],
			[Month07],
			[Month08],
			[Month09],
			[Month10],
			[Month11],
			[Month12],
			[Yearly],
			[Comment],
			[HistoryItemGUID],
			[TransactionID],
			[AdjustmentCategoryID]
		)
	select 
			tmp.[TimeClassID],
			tmp.[FiscalYearID],
			tmp.[DepartmentalBudgetID],
			tmp.[AccountID],
			tmp.[UnitTypeID],
			tmp.[AssumptionID],
			tmp.[Month01],
			tmp.[Month02],
			tmp.[Month03],
			tmp.[Month04],
			tmp.[Month05],
			tmp.[Month06],
			tmp.[Month07],
			tmp.[Month08],
			tmp.[Month09],
			tmp.[Month10],
			tmp.[Month11],
			tmp.[Month12],
			tmp.[Yearly],
			tmp.[Comment],
			tmp.[HistoryItemGUID],
			tmp.[TransactionID],
			tmp.[AdjustmentCategoryID]
	from #dataagg tmp
		left join [clientob].[FactAccountSubtableVar] fctv
			on fctv.TimeClassID = tmp.TimeClassID
			and fctv.FiscalYearID = tmp.FiscalYearID
			and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID
			and fctv.AccountID = tmp.AccountID
			and fctv.UnitTypeID = tmp.UnitTypeID
			and fctv.AssumptionID = tmp.AssumptionID
			and fctv.Comment = tmp.Comment
			and fctv.IsDeleted = tmp.IsDeleted
	where 1=1
		and fctv.TimeClassID is null

--------------------------------------------------------------------------------------------------
-- Invalidate department models
--------------------------------------------------------------------------------------------------
	select @planRefreshList = 'PlanGUID in (''' + dbo.straggr(cast(dep.MemberGUID as nvarchar(36)), ''',''', '') + ''')'
	from #depts dep
	
	exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause = @planRefreshList,@isDebugOnly = 0
	
--------------------------------------------------------------------------------------------------
-- Clean-up
--------------------------------------------------------------------------------------------------
	drop table #depts
	drop table #dataagg

end
GO


---------------------------------------------

-- ob.procClearAllAssumptions
CREATE proc [ob].[procClearAllAssumptions] as
/************************************************************************************************************************
** Author: Bart Lewis
** Create Date: 2015-05-12
** Description: Resets Budget Drop Down Boxes
** Last Modified: 2017-08-08
** GM Release: 2015.3
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID  Date        Author      WI          Description
** 1    2017-04-05  vyaremko    B-15589     Use OB_Budget_IsOpen from [ob].[SystemSetting] instead [dbo].[DBSetting]
** 2    2017-06-06  cbb         B-15886     exclude rvu weights and isstatdriver assumptions
** 3    2017-08-08  vyaremko    B-16694     Rename 'Is Budget Open' to 'Budget Status'
*************************************************************************************************************************/

declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year')

/************** Logging *********************************************************/
declare @higuid uniqueidentifier
declare @Desc nvarchar(200) = 'Reset All Budget Assumptions ' + cast(@FiscalYearID+1 as Nvarchar(4)) + ' Rollover'

declare @RVUid nvarchar(15)
declare @IncExcid nvarchar(15)

select @RVUid = AssumptionID from [fw].[DimAssumption] where MemberGUID = '46c83c8c-fe45-4911-8338-0a2e87474132'
select @IncExcid = AssumptionID from [fw].[DimAssumption] where MemberGUID = 'c70bc8dd-f89c-4afa-bbbd-a454ebfc1a0c'

exec procLogScript @Desc , @higuid output

IF (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status') = 0 -- Closed
BEGIN
	
--Cursor to Delete All Var structures
	BEGIN
		-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
		SET NOCOUNT ON;

		DECLARE @SCHEMA nvarchar(256)
		DECLARE @FactTableName nvarchar(256)
		DECLARE @SQL nvarchar(1024)
		DECLARE @SQL2 nvarchar(1024)
		DECLARE FactTableCursor CURSOR FOR 
			select t.name, (select name from sys.schemas where schema_id = t.schema_id) 
			from sys.tables t 
			where 1=1
				and t.schema_id in
					(
						select schema_id 
						from sys.schemas 
						where name in('ob', 'clientob')
					) 
				and t.name like 'fact%' 
				and t.name like '%var%' 
				and t.name not like '%Snapshot'
				and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') 
				and t.name not like '%map' order by t.name
		open FactTableCursor

		FETCH NEXT FROM FactTableCursor 
		INTO @FactTableName, @SCHEMA
		WHILE @@FETCH_STATUS = 0
		BEGIN

			--set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName
			set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +')'
			set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)'
--		    print @SQL
--		    print @SQL2
		    EXECUTE sp_executesql @SQL
		    EXECUTE sp_executesql @SQL2
		    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
		END

		CLOSE FactTableCursor
		DEALLOCATE FactTableCursor

		--Rebuild Indexes and Update Statistics
		exec [ob].[procOptimizationRebuildIndexesData]
		exec [ob].[procOptimizationRebuildIndexesMapping]
	END
END

RETURN
GO


---------------------------------------------

-- ob.procClearAllComments
CREATE proc [ob].[procClearAllComments] 
	@IsDebugOnly bit=0
as
/************************************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-06-03
** Description: Deletes all comments for selected plans
** Last Modified: 2016-06-03
** GM Release: 2016.3
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID    Date		    Author    WI         Description
*************************************************************************************************************************/

declare @BudgetYear int
select @BudgetYear = Setting+1 
from [dbo].[DBSetting] 
where Name = 'OB_Current_Year'

/************** Logging *********************************************************/
declare @higuid uniqueidentifier
declare @Desc nvarchar(200) = 'Delete comments for ' + cast(@BudgetYear as Nvarchar(4)) + ' Rollover'
exec procLogScript @Desc , @higuid output
/********************************************************************************/

--Cursor to Delete All Var structures
	SET NOCOUNT ON;
	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR
		select distinct
			t.name,
			s.name
		from sys.tables t
			inner join sys.schemas s
				on s.schema_id = t.schema_id
			inner join sys.columns c
				on c.object_id = t.object_id
		where 1=1
			and s.name in ('ob', 'clientob')
			and t.name like 'fact%'
			and t.name like '%var%'
			and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk')
			and t.name not like '%map'
			and t.name not like '%snapshot'
			and c.name in ('TextValue_Formula','TextValue Formula','UnitTypeID')

	open FactTableCursor

	FETCH NEXT FROM FactTableCursor
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	begin
		set @SQL = 
'
delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID = 30
DBCC CHECKIDENT (''' + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)
DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED)
'
		if @IsDebugOnly=1
			begin
				print @SQL
			end
		else
			begin
		    	exec sp_executesql @SQL
			end
	    fetch next from FactTableCursor into @FactTableName, @SCHEMA
	end

	close FactTableCursor
	deallocate FactTableCursor

	--Rebuild Indexes and Update Statistics
	if @IsDebugOnly=0
		begin
			exec [ob].[procOptimizationRebuildIndexesData]
			exec [ob].[procOptimizationRebuildIndexesMapping]
		end
	
	exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] 
		@planTypeGUID = '05512126-3eb6-4da4-af6e-bc2bc2724b8b',
		@source = 'Unknown'
	
	exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] 
		@planTypeGUID = 'b4d1bae4-194d-4499-b573-be9d56cbd802',
		@source = 'Unknown'
		
	exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] 
		@planTypeGUID = '957dd809-6299-4ec2-81fc-5452df805e8e',
		@source = 'Unknown'

return
GO


---------------------------------------------

-- ob.procClearAllNumericAssumptionsRollForwardDropDownBoxes
CREATE proc [ob].[procClearAllNumericAssumptionsRollForwardDropDownBoxes] as
/************************************************************************************************************************
** Author: Bart Lewis
** Create Date: 2015-05-12
** Description: Resets All Assumptions except Drop Down Boxes, those are rolled Forward
** Last Modified: 2015-05-12
** GM Release: 2015.3
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID  Date           Author      WI            Description
** 1    2015-08-18     bjl         n/a           Correct @ColumnCount critera
** 2    2016-05-20     cbb         D-04203       DBCC CHECKIDENT auto reseed instead of at id 1
** 3    2016-06-06     cbb         n/a           reseed to 1, then reseed
** 4    2017-04-05     vyaremko    B-15589       Use OB_Budget_IsOpen from [ob].[SystemSetting] instead [dbo].[DBSetting]
** 5    2017-06-06     cbb         B-15886       add assumption id filters to delete for RVU weight and IsStatDriver and filtered out snapshot var tables
** 6    2017-08-08     vyaremko    B-16694       Rename 'Is Budget Open' to 'Budget Status'
*************************************************************************************************************************/

declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year')

/************** Logging *********************************************************/
declare @higuid uniqueidentifier
declare @Desc nvarchar(200) = 'Reset Non Text Budget Assumptions ' + cast(@FiscalYearID+1 as Nvarchar(4)) + ' Rollover'

-- CID 5 BEGIN
declare @RVUid nvarchar(15)
declare @IncExcid nvarchar(15)

select @RVUid = AssumptionID from [fw].[DimAssumption] where MemberGUID = '46c83c8c-fe45-4911-8338-0a2e87474132'
select @IncExcid = AssumptionID from [fw].[DimAssumption] where MemberGUID = 'c70bc8dd-f89c-4afa-bbbd-a454ebfc1a0c'
-- CID 5 END

exec procLogScript @Desc , @higuid output

IF (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status') = 0 -- Closed
BEGIN

--Cursor to Delete All Var structures
	BEGIN
		-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
		SET NOCOUNT ON;

		DECLARE @SCHEMA nvarchar(256)
		DECLARE @FactTableName nvarchar(256)
		DECLARE @SQL nvarchar(1024)
		DECLARE @SQL1 nvarchar(1024)
		DECLARE @SQL2 nvarchar(1024)
		DECLARE @ColumnCount int
		--Cursor for Clientob Var Fact Tables with 'TextValue_Formula' or'UnitTypeID'
		DECLARE FactTableCursor CURSOR FOR 
			select 
				t.name, 
				s.name,
				Count(c.name)
			from sys.tables t 
			inner join sys.schemas s on s.schema_id = t.schema_id
			inner join sys.columns c on c.object_id = t.object_id
			where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) 
				and t.name like 'fact%' 
				and t.name like '%var%' 
				and t.name not like '%snapshot' 
				and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') 
				and t.name not like '%map'
				and c.name IN('TextValue_Formula','TextValue Formula','UnitTypeID')
			Group by
				t.name, 
				s.name
			order by t.name

		open FactTableCursor

		FETCH NEXT FROM FactTableCursor 
		INTO @FactTableName, @SCHEMA, @ColumnCount
		WHILE @@FETCH_STATUS = 0
		BEGIN
			--Check if 'TextValue_Formula' or just UnitTypeID Exists on Table
			If @ColumnCount = 2 Begin
				set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +') and UnitTypeID<>141 and TextValue_Formula<>''x'''
			End

			IF @ColumnCount = 1 Begin
				set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +') and UnitTypeID<>141'
			End	
			set @SQL1 = 'Update ' + @SCHEMA + '.' + @FactTableName + ' set FiscalYearID=FiscalYearID + 1 where FiscalYearID<>0'

			set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED,1)
						DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED)'

		    --print @SQL
		    --print @SQL2
		    EXECUTE sp_executesql @SQL 
			EXECUTE sp_executesql @SQL1
		    EXECUTE sp_executesql @SQL2
		    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA, @ColumnCount
		END

		CLOSE FactTableCursor
		DEALLOCATE FactTableCursor

		--Rebuild Indexes and Update Statistics
		exec [ob].[procOptimizationRebuildIndexesData]
		exec [ob].[procOptimizationRebuildIndexesMapping]
	END
END

RETURN
GO


---------------------------------------------

-- ob.procClearWorkspace
CREATE proc [ob].[procClearWorkspace] 
	@planGUIDList nvarchar(max)=''
as

/**************************************************************************************
** Author: Corey Becker
** Create Date: 2016-06-03
** Description: Deletes all content in Workspace section of departmental budgets
** Last Modified: 2016-06-03
** GM Release: 2016.3
***************************************************************************************
** Change History
***************************************************************************************
** CID    Date		    Author    WI         Description
**************************************************************************************/

-- Logging ----------------------------------------------------------------------------
	declare @higuid uniqueidentifier
	declare @Desc nvarchar(200) = 'Delete Workspace content in OB Dept Budget models'
	exec procLogScript @Desc , @higuid output

-- Create temp table to hold affected models ------------------------------------------
	create Table #Plans(DepartmentalBudgetID int, ModelGUID uniqueidentifier)

	if (len(@planGUIDList) = 0) 
		begin
			insert into #Plans
				(DepartmentalBudgetID, ModelGUID)
			select dim.DepartmentalBudgetID, dim.MemberGUID
			from ob.DimDepartmentalBudget dim
		end
	else
		begin
			insert into #Plans
				(DepartmentalBudgetID, ModelGUID)
			select dim.DepartmentalBudgetID, dim.MemberGUID
			from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') guids
				inner join ob.DimDepartmentalBudget dim 
					on guids.guid = dim.MemberGUID
		end

-- Delete data ------------------------------------------------------------------------
	delete data
	from [dbo].[MEImprovData] data
		inner join #Plans pl
			on data.ModelGUID = pl.ModelGUID

-- Invalidate model cache -------------------------------------------------------------
	if (len(@planGUIDList) = 0) 
		begin
			exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] 
				@planTypeGUID = '05512126-3eb6-4da4-af6e-bc2bc2724b8b',
				@source = 'Unknown'
		end
	else
		begin
			declare @whereClause nvarchar(max) = 'PlanGUID in ('''+@planGUIDList+''')'
			exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] 
				@xplanWhereClause = @whereClause, 
				@isDebugOnly = 0, 
				@source = 'Unknown'
		end

-- Clean-up ---------------------------------------------------------------------------
	drop table #Plans

return
GO


---------------------------------------------

-- ob.procCreateViewReportStaffingtoGLAccount
CREATE proc ob.procCreateViewReportStaffingtoGLAccount
	@mode nvarchar(100) = 'default'
as
	if (@mode = 'default') begin
		select @mode = cast(PropertyXML.query('//PayRollToGLLinkDollarsConfiguration/text()') as nvarchar(100)) from [dbo].[SystemCenterStep] where Name = 'Payroll to GL Link Selection'
		if (@mode is null or @mode = '') return
	end

	declare @sql nvarchar(max)
	set @sql = 'alter view [ob].[viewReportStaffingtoGLAccount] as
	select * from ob.viewReportStaffingtoGLAccount_' + @mode
	exec(@sql)
GO


---------------------------------------------

-- ob.procDataViewRegisterDimensions
CREATE proc [ob].[procDataViewRegisterDimensions]
	@dvguid uniqueidentifier,
	@isSafeMode bit = 0 --safe mode will skip deletes and only do adds
as
	declare @rdguid uniqueidentifier
	declare @dvsql nvarchar(200)
	select @dvsql = replace(replace(SQLViewName, '[', ''), ']', '') from DataView where DataViewGUID = @dvguid

	--department
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentID')) begin
		print @dvsql + ' - Registering DepartmentID'

		declare @departmentDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'Department')
		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department' when a.SQLColumnName = 'Description' then 'Department Description' else isnull(da.FriendlyName, a.FriendlyName) end 
		from viewScoreAttribute a 
		join ScoreAttributeSetting attrSet on a.DimensionGUID = attrSet.DimensionGUID and a.AttributeGuid = attrSet.AttributeGuid
		left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID 
		where 
			a.DimensionGUID = @departmentDimGuid 
			and (
				(a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined') 
				or a.SQLColumnName in('Name', 'DepartmentCode')
				or attrSet.OBIsUsed = 1
			)
			and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end
	
	--departmental budget
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentalBudgetID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentalBudgetID')) 
	begin
		   declare @departmentalBudgetDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'OB Departmental Budget')
		   insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		   select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentalBudgetID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'OB Departmental Budget'
		   and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		   select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'OB Departmental Budget' and rd.DataViewGUID = @dvguid;
             
		   insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		   select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Departmental Budget' else isnull(da.FriendlyName, a.FriendlyName) end
		   from viewScoreAttribute a
		   left join viewScoreAttribute ia on ia.AttributeGUID = a.InferredAttributeGUID
		   left join ScoreAttributeSetting attrSet on ia.DimensionGUID = attrSet.DimensionGUID and ia.AttributeGuid = attrSet.AttributeGuid
		   left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID 
		   where 
				a.DimensionGUID = @departmentalBudgetDimGuid 
				and (
					(a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 5) and a.SQLColumnName not like '%IsDefined') 
					or isnull(attrSet.OBIsUsed, 0) = 1
					or a.SQLColumnName in('Name')
				)
				and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end
	
	--account
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'AccountID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'AccountID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering AccountID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'AccountID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Account'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Account' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Account' when a.SQLColumnName = 'Description' then 'Account Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Account' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName != 'OBDollarsFinancialReportingCategory') or a.SQLColumnName in('Name', 'AccountCode', 'OBModelSectionName', 'OBUnitsFinancialReporting', 'OBUnitsFinancialReportingLineName', 'OBUnitsFinancialReportingSortOrder', 'OBPayor', 'OBPayorGroup', 'OBUnitType', 'PatientClass') or (@dvsql not like '%statistic%' and a.SQLColumnName in('OBDollarsFinancialReporting', 'OBDollarsFinancialReportingLineName', 'OBDollarsFinancialReportingCategory', 'OBDollarsFinancialReportingSortOrder')))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--job code
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'JobCodeID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'JobCodeID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering JobCodeID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'JobCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Job Code'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Job Code' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Job Code Name' when a.SQLColumnName = 'Description' then 'Job Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Job Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'JobCodeGroup'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--pay code
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Name' when a.SQLColumnName = 'Description' then 'Pay Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayCodeGroup'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--pay code group
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeGroupID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeGroupID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeGroupID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeGroupID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code Group'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code Group' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Group' when a.SQLColumnName = 'Description' then 'Pay Code Group Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code Group' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayClass', 'IsPremium', 'IsOvertime', 'IsAgency', 'IsDirect', 'ProductiveClass'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--employee
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EmployeeID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EmployeeID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EmployeeID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EmployeeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Employee'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Employee' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Employee' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Employee' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end
	
	--time class
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'TimeClassID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'TimeClassID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering TimeClassID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'TimeClassID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Time Class'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Time Class' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Time Class' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Time Class' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--fiscal year
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalYearID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalYearID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalYearID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalYearID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Year'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Year' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Year' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Year' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--fiscal month
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalMonthID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalMonthID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalMonthID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalMonthID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Month'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Month' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Month' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Month' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'FiscalMonthCode'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--date
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DateID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DateID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DateID'
		
		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DateID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Date'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Date' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Date' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Date' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'CalendarDateTime', 'CalendarMonth', 'CalendarMonthName', 'CalendarYear', 'DayNameOfWeek', 'DayNumberOfMonth', 'FiscalYear', 'IsWeekDay'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

	--unit type
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'UnitTypeID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'UnitTypeID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering UnitTypeID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'UnitTypeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Unit Type'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Unit Type' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Unit Type' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Unit Type' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --provider
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'ProviderID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'ProviderID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering ProviderID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'ProviderID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Provider'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Provider' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Provider' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Provider' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'NameFirst', 'NameLast', 'ProviderCode', 'Type', 'WorkWeekOverrideID'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --physician specialty
    if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PhysicianSpecialtyID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PhysicianSpecialtyID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PhysicianSpecialtyID'
		
		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PhysicianSpecialtyID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Physician Specialty'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Physician Specialty' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Physician Specialty' when a.SQLColumnName = 'Description' then 'Physician Specialty Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Physician Specialty' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName not in('RVUTarget', 'SpecialtyGroup')) or a.SQLColumnName in('Name', 'PhysicianSpecialtyCode', 'Description'))
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --OB Forecast Detail
	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'OBForecastDetailID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'OBForecastDetailID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering OBForecastDetailID'
		
		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'OBForecastDetailID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'OB Forecast Detail'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'OB Forecast Detail' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'OB Forecast Detail' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'OB Forecast Detail' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName ='Name')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --System
    declare @systemGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'System')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'SystemID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'SystemID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering SystemID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'SystemID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'System'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DimensionGUID = rd.DimensionGUID where d.GlobalID = 'System' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'System' when a.SQLColumnName = 'Code' then 'System Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @systemGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Entity
    declare @entityGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Entity')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EntityID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EntityID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EntityID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EntityID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Entity'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Entity' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Entity' when a.SQLColumnName = 'Code' then 'Entity Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @entityGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 1
    declare @departmentRollup1GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 1')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup1ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup1ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup1ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup1ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 1'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 1' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 1' when a.SQLColumnName = 'Code' then 'Department Rollup 1 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup1GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 2
    declare @departmentRollup2GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 2')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup2ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup2ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup2ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup2ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 2'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 2' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 2' when a.SQLColumnName = 'Code' then 'Department Rollup 2 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup2GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 3
    declare @departmentRollup3GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 3')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup3ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup3ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup3ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup3ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 3'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 3' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 3' when a.SQLColumnName = 'Code' then 'Department Rollup 3 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup3GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 4
    declare @departmentRollup4GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 4')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup4ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup4ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup4ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup4ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 4'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 4' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 4' when a.SQLColumnName = 'Code' then 'Department Rollup 4 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup4GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 5
    declare @departmentRollup5GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 5')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup5ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup5ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup5ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup5ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 5'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 5' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 5' when a.SQLColumnName = 'Code' then 'Department Rollup 5 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup5GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end

    --Department Rollup 6
    declare @departmentRollup6GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 6')

	if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup6ID')) 
	or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup6ID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup6ID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup6ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 6'
		and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID);
		select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 6' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 6' when a.SQLColumnName = 'Code' then 'Department Rollup 6 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup6GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code')
		and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID))
	end
    
	if (@isSafeMode = 0) begin
		--ensure settings exist for inferred attributes
		exec dbo.procScoreAttributeSettingAddMissing

		--unregister not used attributes
		delete ra
		from
			RESQLReportRegisteredDimension rd
			inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID
			inner join ScoreDimension d on d.DimensionGUID = rd.DimensionGUID
			inner join ScoreAttributeSetting sas on sas.AttributeGUID = ra.AttributeGUID
		where
			d.GlobalID in('Department', 'OB Departmental Bduget')
			and rd.DataViewGUID = @dvguid
			and sas.OBIsUsed = 0
			and sas.IsCustom = 1

		--remove duplicates
		while (exists(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1)) begin
			delete from resqlreportregisteredattribute where registeredattributeguid in(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1)
		end
	end
GO


---------------------------------------------

-- ob.procDataViewRegisterDimensionsAll
CREATE proc ob.procDataViewRegisterDimensionsAll
as
	set nocount on

	declare @dvguid uniqueidentifier
	declare crsViews cursor fast_forward for
		select distinct
			dv.DataViewGUID
		from 
			DataView dv 
		where 
			dv.Name like 'OB %'

	 open crsViews
	 fetch next from crsViews into @dvguid

	 while (@@fetch_status = 0) begin
		exec ob.procDataViewRegisterDimensions @dvguid
		fetch next from crsViews into @dvguid
	 end

	 close crsViews
	 deallocate crsViews
GO


---------------------------------------------

-- ob.procDeleteDimensionData
CREATE PROCEDURE [ob].[procDeleteDimensionData]
AS

/************************************************************
** Author: unknown
** Create Date: Unknown
** Description: Deletes all OB dimensions that are specified by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES
** Last Modified: 2014-10-02
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-10-02	akk		64597	Adding new dimensions
** 2		2014-02-18	akk		D-01495 Filtering out not specified member
** 3		2014-07-22	akk		D-01940	Clearing out accountid
** 4		2014-10-02	JG		B-02929	Clearing out Snapshot and Allocation dimensions
** 5		2015-02-11	akk				Clearing out testing members from OB Forecast Detail
** 6		2015-11-06	akk				Deleting global assumptions
*************************************************************/


BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	declare @nextid int
	select @nextid = 1
	
	--==== BEGIN CID 1 ====
--	delete from ob.DimDepartmentalBudget
--	DBCC CHECKIDENT ('ob.DimDepartmentalBudget', RESEED, @nextid)

--==== BEGIN CID 2 ====
	delete from [ob].[DimOBGlobalStatistics] where OBGlobalStatisticID<>0
--==== END CID 2 ====
	DBCC CHECKIDENT ('ob.DimOBGlobalStatistics', RESEED, @nextid)

--==== BEGIN CID 4 ====
	delete from [ob].[DimOBSnapshot] where OBSnapshotID<>0
	DBCC CHECKIDENT ('ob.DimOBSnapshot', RESEED, @nextid)
	delete from [ob].[DimOBAllocation] where OBAllocationID<>0
	DBCC CHECKIDENT ('ob.DimOBAllocation', RESEED, @nextid)
	delete from [ob].[DimOBAllocationBasis] where OBAllocationBasisID<>0
	DBCC CHECKIDENT ('ob.DimOBAllocationBasis', RESEED, @nextid)
--==== END CID 4 ====		
	

	--==== END CID 1 ====
	--==== BEGIN CID 3 ====
	update [ob].[DimOBForecastDetail]
	set AccountID=0,SecondaryAccountID=0
	exec [dbo].[procScoreDimensionCacheRefresh] '7997659c-8a30-4d1e-86d2-0afb41c9e2fc'
	--==== END CID 3 ====

	--==== BEGIN CID 5 ====
	delete from [ob].[DimOBForecastDetail]
	where Name like '%zzTest%'
	
	--==== END CID 5 ====	
	--==== BEGIN CID 6 ====
	delete from [dbo].[GlobalAssumption]
	--==== END CID 6 ====
	--Rebuild Indexes and Update Statistics
	exec [ob].[procOptimizationRebuildIndexesDimensions]
END

RETURN
GO


---------------------------------------------

-- ob.procDeleteExceptionsDataWithoutDimensionMembers
/************************************************************
** Author: jgerber
** Create Date: 2014-09-18
** Description: Deletes SL data that does not have dimension members
** Last Modified: 2014-09-18
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

create proc [ob].[procDeleteExceptionsDataWithoutDimensionMembers]

as 

--***Fact Account*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactAccount] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
		
-- Account Dimension
	delete
		data
	from 
		[clientob].[FactAccount] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID
	where 
		dim.MemberGUID is null	
		
		
--***Fact Staffing PC*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
		
-- Job Code Dimension
	delete
		data
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimJobCode] dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID
	where 
		dim.MemberGUID is null			
	
		
-- Pay Code Dimension
	delete
		data
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimPayCode] dim with (readuncommitted) on dim.PayCodeID = data.PayCodeID
	where 
		dim.MemberGUID is null			
		
	
-- Pay Code Group Dimension
	delete
		data
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimPayCodeGroup] dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID
	where 
		dim.MemberGUID is null			
		
		
-- Employee Dimension
	delete
		data
	from 
		[clientob].[FactStaffingPC] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimEmployee] dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID
	where 
		dim.MemberGUID is null				
		
		
--***Fact Provider*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
		
-- Provider Dimension
	delete
		data
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimProvider] dim with (readuncommitted) on dim.ProviderID = data.ProviderID
	where 
		dim.MemberGUID is null			
		
		
-- Forecast Detail Dimension
	delete
		data
	from 
		[clientob].[FactProvider] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null			
		
		
--***Fact Charge Code*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactCDM] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
		
-- Charge Code Dimension
	delete
		data
	from 
		[clientob].[FactCDM] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [fw].[DimChargeCode] dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID
	where 
		dim.MemberGUID is null			
				

--***Fact Reporting*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactReportingMonthly] data with (readuncommitted)
		left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
	where 
		db.MemberGUID is null
		
		
-- Financial Reporting Dimension
	delete
		data
	from 
		[clientob].[FactReportingMonthly] data with (readuncommitted)
		inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID
		left join [ob].[DimFinancialReporting] dim with (readuncommitted) on dim.FinancialReportingID = data.FinancialReportingID
	where 
		dim.MemberGUID is null			
		
				
--***Fact Global Statistics*********************************************
-- Department Dimension
	delete
		data
	from 
		[clientob].[FactGlobalStatistics] data with (readuncommitted)
		left join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID
	where 
		db.MemberGUID is null
		
		
-- Global Statistics Dimension
	delete
		data
	from 
		[clientob].[FactGlobalStatistics] data with (readuncommitted)
		inner join[ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID
		left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID = data.OBGlobalStatisticID
	where 
		dim.MemberGUID is null	
	
		
--***Fact Service Line*********************************************
-- Service Line Plan Dimension
	delete
		data
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		left join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
	where 
		db.MemberGUID is null
		
		
-- Modeling Service Line Dimension
	delete
		data
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
		left join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID
	where 
		dim.MemberGUID is null	
		
		
-- Forecast Detail Dimension
	delete
		data
	from 
		[clientob].[FactServiceLine] data with (readuncommitted)
		inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null			
				

--***Fact Reimbursement Account*********************************************
-- Reimbursement Plan Dimension
	delete
		data
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
	where 
		db.MemberGUID is null
		
		
-- Account Dimension
	delete
		data
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID
	where 
		dim.MemberGUID is null	
		
		
-- Patient Reimbursement Group Dimension
	delete
		data
	from 
		[clientob].[FactReimbursementAccount] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
	where 
		dim.MemberGUID is null			


--***Fact Reimbursement *********************************************
-- Reimbursement Plan Dimension
	delete
		data
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
	where 
		db.MemberGUID is null
		
		
-- Forecast Detail Dimension
	delete
		data
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID
	where 
		dim.MemberGUID is null	
		
			
-- Patient Reimbursement Group Dimension
	delete
		data
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID
	where 
		dim.MemberGUID is null			
				
	
-- Payor Group Dimension
	delete
		data
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID
	where 
		dim.MemberGUID is null			
				
		
-- Payor Dimension
	delete
		data
	from 
		[clientob].[FactReimbursement] data with (readuncommitted)
		inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID
		left join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID
	where 
		dim.MemberGUID is null			
								
RETURN
GO


---------------------------------------------

-- ob.procDeleteFactData
CREATE PROCEDURE [ob].[procDeleteFactData]
AS
/************************************************************
** Author: unknown
** Create Date: Unknown
** Description: Deletes all CAP Fact tables - used only for GM releases - NEVER RUN ON CLIENT DATABASES
** Last Modified: 2013-11-07
** GM Release: 2013-11-19
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-11-07	akk		65765	Filtering out mapping tables from the delete
**
*************************************************************/

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE @SQL2 nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
--==== BEGIN CID 1 ====
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob') ) and t.name like 'fact%' and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') and t.name not like '%map' order by t.name
--==== END CID 1 ====
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName
		set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)'
	    --print @SQL
	    --print @SQL2
	    EXECUTE sp_executesql @SQL 
	    EXECUTE sp_executesql @SQL2
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor

	truncate table [ob].[ReconciliationTarget]
	truncate table [ob].[JobCodeReconciliationTarget]
	truncate table [ob].[PayCodeReconciliationTarget]
	truncate table [ob].[StatisticsEntityReconciliationTarget]

	--Rebuild Indexes and Update Statistics
	exec [ob].[procOptimizationRebuildIndexesData]
	exec [ob].[procOptimizationRebuildIndexesMapping]
END


RETURN
GO


---------------------------------------------

-- ob.procDepartmentalBudgetMaintenance
CREATE proc [ob].[procDepartmentalBudgetMaintenance]
                @planGUIDList nvarchar(max),
                @isForcingRefresh bit = 0
as

--///////////////////  DEPRECATED USE SYSTEM CENTER /////////////////// 


--                declare @budgetSectionGUID uniqueidentifier
--                select @budgetSectionGUID = MemberGUID from ob.DimDepartmentalBudgetPH (readuncommitted) where Name = 'Current Budget'
--
----if self placeholder exists, assume this proc is already done and can exit
--                if (@isForcingRefresh = 0) begin
--                                if((select count(*) from ScoreFillin FI (readuncommitted) where FI.ModelGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs) and FI.PlaceholderSectionMemberGUID = @budgetSectionGUID) > 0) begin
--                                                return
--                                end
--                end
--
----set departmental budget self placeholder
--                insert into ScoreFillin(ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName)
--                select
--                                P.PlanGUID,
--                                @budgetSectionGUID,
--                                0,
--                                P.PlanGUID,
--                                P.Name
--                from
--                                XPlan P (readuncommitted)
--                where
--                                P.PlanGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs)
--                                and not exists(select 1 from ScoreFillin FI (readuncommitted) where FI.ModelGUID = P.PlanGUID and FI.PlaceholderSectionMemberGUID = @budgetSectionGUID)
--                                
----get year for year fill-ins
--                declare @yearSectionGUID uniqueidentifier
--                select @yearSectionGUID = MemberGUID from fw.DimFiscalYearPH (readuncommitted) where Name = 'Selected Year'
----set dept budget year fill-ins
--                insert into ScoreFillin(ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName)
--                select
--                                P.MemberGUID,
--                                @yearSectionGUID,
--                                (FY.FiscalYearID - P.BaseYear + 1),
--                                FY.MemberGUID,
--                                FY.Name
--                from
--                                ob.DimDepartmentalBudget P (readuncommitted)
--                                inner join fw.DimFiscalYear FY (readuncommitted) on FY.FiscalYearID = P.BaseYear - 1 or FY.FiscalYearID = P.BaseYear or FY.FiscalYearID = P.BaseYear + 1
--                where
--                                P.MemberGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs)
--                                and not exists(select 1 from ScoreFillin FI (readuncommitted) where FI.ModelGUID = P.MemberGUID and FI.PlaceholderSectionMemberGUID = @yearSectionGUID)
GO


---------------------------------------------

-- ob.procDepartmentalBudgetMaintenanceAll
CREATE proc [ob].[procDepartmentalBudgetMaintenanceAll]
as
	declare @planguids nvarchar(max) 
	select @planguids = coalesce(@planguids + ',','') + cast(MemberGUID as nvarchar(128)) from ob.DimDepartmentalBudget (readuncommitted) where MemberGUID not in(select p.PlanGUID from XPlan p (readuncommitted) where p.IsDeletedPlan = 1)

	exec ob.procDepartmentalBudgetMaintenance @planguids, 1
GO


---------------------------------------------

-- ob.procExceptionsDepartmentalBudgetPopulate
CREATE PROCEDURE [ob].[procExceptionsDepartmentalBudgetPopulate]
	@ClearAcknowledged BIT = 0,
	@OBExceptionsID INT = NULL
AS
/************************************************************
** Author: akowalski
** Create Date: 2014-04-30
** Description: Populates Departmental Budget Exception Table
** Last Modified: 2016-08-02
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-10-09	JG				Adjusting the widget height of the report
** 2		2015-01-08	akk				Changing proc to not use view for better performance
** 3		2016-08-02	kf				Add @OBExceptionsID parameter, remove cursor
** 4		2016-08-03	kf				Remove widgets update
** 5		2016-08-11	kf				Remove duplications
** 6		2019-02-21	GF				Remove backup of exceptions
*************************************************************/

DECLARE @dbname NVARCHAR(1000) = (DB_Name())
--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactDepartmentBudgetExceptions', 'ob'

-- Logging ************************************************************************
DECLARE @higuid UNIQUEIDENTIFIER
EXEC procLogScript 'Updating Department Budget Exceptions', @higuid OUTPUT

-- Create new exceptions temp table ********************************************

CREATE TABLE #NewExceptionsToInsert(
	[OBExceptionsID] [int] NOT NULL DEFAULT ((0)),
	[DepartmentalBudgetID] [int] NOT NULL DEFAULT ((0)),
	[Detail] [nvarchar](2000) NOT NULL DEFAULT ('')
)

DECLARE @isExecuting BIT = 1
DECLARE @Model NVARCHAR(256) = 'Departmental Budget'
DECLARE @ModelIDName NVARCHAR(256) = '[DepartmentalBudgetID]'
DECLARE @sqli VARCHAR(MAX)
DECLARE @OBExceptionsIDStr VARCHAR(MAX)
DECLARE @View NVARCHAR(100)

DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100))

INSERT INTO @exceptions (OBExceptionsID, ViewName)
SELECT OBExceptionsID, ViewName
FROM [ob].[DimOBExceptions] e
WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID)

DECLARE @Count INT
SELECT @Count = COUNT(1) FROM @exceptions

WHILE @Count > 0
BEGIN
  SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName
  FROM @exceptions

  SET @sqli = 
		'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail])
			SELECT DISTINCT
			' + @OBExceptionsIDStr + ' as OBExceptionsID,
			e.' + @ModelIDName + ',
			e.detail
			FROM ' + @View + ' e'
		
		IF @isExecuting = 1 BEGIN
			EXEC(@sqli)
		END ELSE BEGIN
			PRINT @sqli
		END

  DELETE FROM @exceptions
  WHERE OBExceptionsID = @OBExceptionsIDStr

  SET @Count -= 1
END

DECLARE @seedID INT

IF(@ClearAcknowledged=1)
BEGIN
	DELETE FROM [ob].[FactDepartmentBudgetExceptions]
	WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)

	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactDepartmentBudgetExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactDepartmentBudgetExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactDepartmentBudgetExceptions]
	([OBExceptionsID], [DepartmentalBudgetID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT
	  e.OBExceptionsID,
	  e.DepartmentalBudgetID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
END
ELSE
BEGIN
	DELETE FROM [ob].[FactDepartmentBudgetExceptions]
	WHERE Acknowledged = 0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)
	
	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactDepartmentBudgetExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactDepartmentBudgetExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactDepartmentBudgetExceptions]
	([OBExceptionsID], [DepartmentalBudgetID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT
	  e.OBExceptionsID,
	  e.DepartmentalBudgetID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
	WHERE NOT EXISTS
		(SELECT 1 FROM [ob].[FactDepartmentBudgetExceptions] target
			WHERE e.DepartmentalBudgetID=target.DepartmentalBudgetID
			AND e.OBExceptionsID=target.OBExceptionsID
			AND e.detail=target.detail
		)
END
GO


---------------------------------------------

-- ob.procExceptionsGlobalStatsPopulate
CREATE PROCEDURE [ob].[procExceptionsGlobalStatsPopulate] 
	@ClearAcknowledged BIT = 0,
	@OBExceptionsID INT = NULL
AS
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Populates Global Stats Exception Table
** Last Modified: 2015-08-02
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2016-08-02  kf				Add @OBExceptionsID parameter, remove cursor
** 2		2016-08-03  kf				Remove widgets update
** 3		2016-08-11  kf				Remove duplications
** 4		2019-02-21	GF				Remove backup of exceptions
*************************************************************/

DECLARE @dbname NVARCHAR(1000) = (DB_Name())
--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatisticExceptions', 'ob'

-- Logging ************************************************************************
DECLARE @higuid UNIQUEIDENTIFIER
EXEC procLogScript 'Updating Global Stats Exceptions' , @higuid OUTPUT

-- Create new exceptions temp table ********************************************

CREATE TABLE #NewExceptionsToInsert(
	[OBExceptionsID] [int] NOT NULL DEFAULT ((0)),
	[OBGlobalStatisticsPlanID] [int] NOT NULL DEFAULT ((0)),
	[Detail] [nvarchar](2000) NOT NULL DEFAULT ('')
) 

DECLARE @isExecuting BIT = 1
DECLARE @Model NVARCHAR(256) = 'Global Statistics'
DECLARE @ModelIDName NVARCHAR(256) = '[OBGlobalStatisticsPlanID]'
DECLARE @sqli VARCHAR(MAX)
DECLARE @OBExceptionsIDStr VARCHAR(MAX)	
DECLARE @View NVARCHAR(100)

DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100))

INSERT INTO @exceptions (OBExceptionsID, ViewName)
SELECT OBExceptionsID, ViewName
FROM [ob].[DimOBExceptions] e
WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID)

DECLARE @Count INT
SELECT @Count = COUNT(1) FROM @exceptions

WHILE @Count > 0
BEGIN
  SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName
  FROM @exceptions

  SET @sqli = 
		'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail])
			SELECT DISTINCT
			' + @OBExceptionsIDStr + ' as OBExceptionsID,
			e.' + @ModelIDName + ',
			e.detail
			FROM ' + @View + ' e'					
		
		IF @isExecuting = 1 BEGIN
			EXEC(@sqli)
		END ELSE BEGIN
			PRINT @sqli
		END

  DELETE FROM @exceptions
  WHERE OBExceptionsID = @OBExceptionsIDStr

  SET @Count -= 1
END

DECLARE @seedID INT

IF(@ClearAcknowledged=1)
BEGIN
	DELETE FROM [ob].[FactGlobalStatisticExceptions]
	WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)

	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactGlobalStatisticExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactGlobalStatisticExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactGlobalStatisticExceptions]
	([OBExceptionsID], [OBGlobalStatisticsPlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT 
	  e.OBExceptionsID,
	  e.OBGlobalStatisticsPlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
END
ELSE
BEGIN
	DELETE FROM [ob].[FactGlobalStatisticExceptions]
	WHERE Acknowledged = 0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)
	
	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactGlobalStatisticExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactGlobalStatisticExceptions", RESEED, @seedID)
		
	INSERT INTO [ob].[FactGlobalStatisticExceptions]
	([OBExceptionsID], [OBGlobalStatisticsPlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT 
	  e.OBExceptionsID,
	  e.OBGlobalStatisticsPlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
	WHERE NOT EXISTS
		(SELECT 1 FROM [ob].[FactGlobalStatisticExceptions] target
			WHERE e.OBGlobalStatisticsPlanID=target.OBGlobalStatisticsPlanID
			AND e.OBExceptionsID=target.OBExceptionsID
			AND e.detail=target.detail
		)
END
GO


---------------------------------------------

-- ob.procExceptionsReimbursementPopulate
CREATE PROCEDURE [ob].[procExceptionsReimbursementPopulate] 
	@ClearAcknowledged BIT = 0,
	@OBExceptionsID INT = NULL
AS
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Populates Reimbursement Exception Table
** Last Modified: 2016-08-02
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2016-08-02	kf				Add @OBExceptionsID parameter, remove cursor
** 2		2016-08-03	kf				Remove widgets update
** 3		2016-08-11	kf				Remove duplications
** 4		2019-02-21	GF				Remove backup of exceptions
*************************************************************/

DECLARE @dbname NVARCHAR(1000) = (DB_Name())
--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementExceptions', 'ob'

-- Logging ************************************************************************
DECLARE @higuid UNIQUEIDENTIFIER
EXEC procLogScript 'Updating Reimbursement Exceptions' , @higuid OUTPUT

-- Create new exceptions temp table ********************************************

CREATE TABLE #NewExceptionsToInsert(
	[OBExceptionsID] [int] NOT NULL DEFAULT ((0)),
	[OBReimbursementPlanID] [int] NOT NULL DEFAULT ((0)),
	[Detail] [nvarchar](2000) NOT NULL DEFAULT ('')
)

DECLARE @isExecuting BIT = 1
DECLARE @Model NVARCHAR(256) = 'Reimbursement'
DECLARE @ModelIDName NVARCHAR(256) = '[OBReimbursementPlanID]'
DECLARE @sqli VARCHAR(MAX)
DECLARE @OBExceptionsIDStr VARCHAR(MAX)
DECLARE @View NVARCHAR(100)

DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100))

INSERT INTO @exceptions (OBExceptionsID, ViewName)
SELECT OBExceptionsID, ViewName
FROM [ob].[DimOBExceptions] e
WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID)

DECLARE @Count INT
SELECT @Count = COUNT(1) FROM @exceptions

WHILE @Count > 0
BEGIN
  SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName
  FROM @exceptions

  SET @sqli = 
		'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail])
			SELECT DISTINCT
			' + @OBExceptionsIDStr + ' as OBExceptionsID,
			e.' + @ModelIDName + ',
			e.detail
			FROM ' + @View + ' e'
		
		IF @isExecuting = 1 BEGIN
			EXEC(@sqli)
		END ELSE BEGIN
			PRINT @sqli
		END

  DELETE FROM @exceptions
  WHERE OBExceptionsID = @OBExceptionsIDStr

  SET @Count -= 1
END

DECLARE @seedID INT

IF(@ClearAcknowledged=1)
BEGIN
	DELETE FROM [ob].[FactReimbursementExceptions]
	WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)

	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactReimbursementExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactReimbursementExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactReimbursementExceptions]
	([OBExceptionsID], [OBReimbursementPlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT
	  e.OBExceptionsID,
	  e.OBReimbursementPlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
END
ELSE
BEGIN
	DELETE FROM [ob].[FactReimbursementExceptions]
	WHERE Acknowledged=0  AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)
	
	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactReimbursementExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactReimbursementExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactReimbursementExceptions]
	([OBExceptionsID], [OBReimbursementPlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT 
	  e.OBExceptionsID,
	  e.OBReimbursementPlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
	WHERE NOT EXISTS
		(SELECT 1 FROM [ob].[FactReimbursementExceptions] target
			WHERE e.OBReimbursementPlanID=target.OBReimbursementPlanID
			AND e.OBExceptionsID=target.OBExceptionsID
			AND e.detail=target.detail
		)
END
GO


---------------------------------------------

-- ob.procExceptionsServiceLinePopulate
CREATE PROCEDURE [ob].[procExceptionsServiceLinePopulate]
	@ClearAcknowledged BIT = 0,
	@OBExceptionsID INT = NULL
AS
/************************************************************
** Author: akowalski
** Create Date: 2015-01-09
** Description: Populates Service Line Exception Table
** Last Modified: 2016-08-02
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2016-08-02	kf				Add @OBExceptionsID parameter, remove cursor
** 2		2016-08-03	kf				Remove widgets update
** 3		2016-08-11	kf				Remove duplications
** 4		2019-02-21	GF				Remove backup of exceptions
*************************************************************/

DECLARE @dbname NVARCHAR(1000) = (DB_Name())
--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineExceptions', 'ob'

-- Logging ************************************************************************
DECLARE @higuid UNIQUEIDENTIFIER
EXEC procLogScript 'Updating Service Line Exceptions' , @higuid OUTPUT

-- Create new exceptions temp table ********************************************

CREATE TABLE #NewExceptionsToInsert(
	[OBExceptionsID] [int] NOT NULL DEFAULT ((0)),
	[OBServiceLinePlanID] [int] NOT NULL DEFAULT ((0)),
	[Detail] [nvarchar](2000) NOT NULL DEFAULT ('')
)

DECLARE @isExecuting BIT = 1
DECLARE @Model NVARCHAR(256) = 'Service Line'
DECLARE @ModelIDName NVARCHAR(256) = '[OBServiceLinePlanID]'
DECLARE @sqli VARCHAR(MAX)
DECLARE @OBExceptionsIDStr VARCHAR(MAX)	
DECLARE @View NVARCHAR(100)

DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100))

INSERT INTO @exceptions (OBExceptionsID, ViewName)
SELECT OBExceptionsID, ViewName
FROM [ob].[DimOBExceptions] e
WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID)

DECLARE @Count INT
SELECT @Count = COUNT(1) FROM @exceptions

WHILE @Count > 0
BEGIN
  SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName
  FROM @exceptions
		
  SET @sqli = 
		'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail])
			SELECT DISTINCT
			' + @OBExceptionsIDStr + ' as OBExceptionsID,
			e.' + @ModelIDName + ',
			e.detail
			FROM ' + @View + ' e'
		
		IF @isExecuting = 1 BEGIN
			EXEC(@sqli)
		END ELSE BEGIN
			PRINT @sqli
		END

  DELETE FROM @exceptions
  WHERE OBExceptionsID = @OBExceptionsIDStr

  SET @Count -= 1
END

DECLARE @seedID INT

IF(@ClearAcknowledged=1)
BEGIN    
	DELETE FROM [ob].[FactServiceLineExceptions]
	WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)

	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactServiceLineExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactServiceLineExceptions", RESEED, @seedID)
		
	INSERT INTO [ob].[FactServiceLineExceptions]
	([OBExceptionsID], [OBServiceLinePlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT 
	  e.OBExceptionsID,
	  e.OBServiceLinePlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
END
ELSE
BEGIN
	DELETE FROM [ob].[FactServiceLineExceptions]
	WHERE Acknowledged=0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID)
	
	SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactServiceLineExceptions])+1
	IF @seedID IS NULL
	BEGIN
	  SET @seedID=1
	END
	DBCC CHECKIDENT ("ob.FactServiceLineExceptions", RESEED, @seedID)
	
	INSERT INTO [ob].[FactServiceLineExceptions]
	([OBExceptionsID], [OBServiceLinePlanID], [Detail], [Acknowledged], [HistoryItemGuid])
	SELECT 
	  e.OBExceptionsID,
	  e.OBServiceLinePlanID,
	  e.detail,
	  0 as Acknowledged,
	  @higuid as HistoryItemGUID
	FROM #NewExceptionsToInsert e
	WHERE NOT EXISTS
		(SELECT 1 FROM [ob].[FactServiceLineExceptions] target
			WHERE e.OBServiceLinePlanID=target.OBServiceLinePlanID
			AND e.OBExceptionsID=target.OBExceptionsID
			AND e.detail=target.detail
		)
END
GO


---------------------------------------------

-- ob.procExceptionsUpdateExplanationDashboardWidget
CREATE proc ob.procExceptionsUpdateExplanationDashboardWidget 
as
/************************************************************
** Author: akowalski
** Create Date: 2015-02-02
** Description: Updates the exception explanation dashboard widget with the latest information from the dimension
** Last Modified: 2015-02-02
** GM Release: 2015.2
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
*************************************************************/

DECLARE @isExecuting bit = 1
DECLARE @Model nvarchar(200)
DECLARE @Name nvarchar(400)
DECLARE @Severity nvarchar(200)
DECLARE @Description nvarchar(max)
DECLARE @Resolution nvarchar(max)
DECLARE @sqli nvarchar(max) = '<Announcement xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Strata.CS.Jazz.UI.Desktop.Widgets"><AnnouncementText>'

DECLARE Models CURSOR FOR 
	select distinct model from [ob].[DimOBExceptions] where OBExceptionsID<>0 order by Model
	
open Models

FETCH NEXT FROM Models 
	INTO @Model
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	SET @sqli = @sqli + '&lt;p&gt;&lt;strong&gt;&lt;u&gt;&lt;font size="3"&gt;' + @Model + '&lt;/font&gt;&lt;/u&gt;&lt;/strong&gt;&lt;/p&gt;'

	DECLARE Exceptions CURSOR FOR 
		select Name,Severity,Description,Resolution from [ob].[DimOBExceptions] where OBExceptionsID<>0 and model=@Model order by severity,SortOrder

	open Exceptions

		FETCH NEXT FROM Exceptions 
			INTO @Name, @Severity, @Description, @Resolution
		WHILE (@@FETCH_STATUS = 0) 
			BEGIN
				SET @sqli = @sqli + '&lt;p&gt;&lt;strong&gt;&lt;u&gt;' + @Name + '&lt;br&gt;&lt;/u&gt;Severity:&lt;/strong&gt; ' + @Severity + '&lt;br&gt;&lt;strong&gt;Description:&lt;/strong&gt; ' + @Description + '&amp;nbsp;&amp;nbsp;&lt;br&gt;&lt;strong&gt;Resolution:&lt;/strong&gt; ' + @Resolution + '&lt;/p&gt;'
				
				FETCH NEXT FROM Exceptions INTO @Name, @Severity, @Description, @Resolution
			END
		CLOSE Exceptions
		DEALLOCATE Exceptions
	FETCH NEXT FROM Models INTO @Model
	END
CLOSE Models
DEALLOCATE Models

SET @sqli = @sqli + '</AnnouncementText></Announcement>'

if @isExecuting = 1 begin
	update [dbo].[DesktopWidget]
	set WidgetXML=@sqli
	where DesktopWidgetGUID='cd85554c-c566-4e02-8a55-57a6075d047e'
end else begin
	print @sqli
end

RETURN
GO


---------------------------------------------

-- ob.procFactPayrollToAccountCrosswalkAddMissing
create proc ob.procFactPayrollToAccountCrosswalkAddMissing
as
	if (exists(select 1 from ob.SystemSetting where Name = 'Payroll To GL Link Dollars Configuration' and Value = 'BothUnique')) begin
		;with groupedRecords as(
			select 
				jc.JobCodeGroupID, 
				cw.PayCodeGroupID, 
				cw.AccountID, 
				cw.UnitTypeID 
			from 
				[clientob].[FactPayrollToAccountCrosswalk] cw 
				inner join fw.DimJobCode jc on jc.JobCodeID = cw.JobCodeID 
			where 
				cw.UnitTypeID = 34 
			group by 
				jc.JobCodeGroupID, 
				cw.PayCodeGroupID, 
				cw.AccountID, 
				cw.UnitTypeID
		)
		insert into clientob.FactPayrollToAccountCrosswalk (JobCodeID, PayCodeGroupID, AccountID, UnitTypeID)
		select
			jc.JobCodeID, 
			cw.PayCodeGroupID, 
			cw.AccountID, 
			cw.UnitTypeID 
		from
			groupedRecords cw
			inner join fw.DimJobCode jc on jc.JobCodeGroupID = cw.JobCodeGroupID
		where
			not exists(select 1 from [clientob].[FactPayrollToAccountCrosswalk] ex where ex.JobCodeID = jc.JobCodeID and ex.PayCodeGroupID = cw.PayCodeGroupID and ex.AccountID = cw.AccountID and ex.UnitTypeID = cw.UnitTypeID)
	end

	if (exists(select 1 from ob.SystemSetting where Name = 'Payroll To GL Link Hours Configuration' and Value = 'BothUnique')) begin
		;with groupedRecords as(
			select 
				jc.JobCodeGroupID, 
				cw.PayCodeGroupID, 
				cw.AccountID, 
				cw.UnitTypeID 
			from 
				[clientob].[FactPayrollToAccountCrosswalk] cw 
				inner join fw.DimJobCode jc on jc.JobCodeID = cw.JobCodeID 
			where 
				cw.UnitTypeID = 51
			group by 
				jc.JobCodeGroupID, 
				cw.PayCodeGroupID, 
				cw.AccountID, 
				cw.UnitTypeID
		)
		insert into clientob.FactPayrollToAccountCrosswalk (JobCodeID, PayCodeGroupID, AccountID, UnitTypeID)
		select
			jc.JobCodeID, 
			cw.PayCodeGroupID, 
			cw.AccountID, 
			cw.UnitTypeID 
		from
			groupedRecords cw
			inner join fw.DimJobCode jc on jc.JobCodeGroupID = cw.JobCodeGroupID
		where
			not exists(select 1 from [clientob].[FactPayrollToAccountCrosswalk] ex where ex.JobCodeID = jc.JobCodeID and ex.PayCodeGroupID = cw.PayCodeGroupID and ex.AccountID = cw.AccountID and ex.UnitTypeID = cw.UnitTypeID)
	end
GO


---------------------------------------------

-- ob.procFactReportAccountWithStaffingDetailInsert
CREATE proc ob.procFactReportAccountWithStaffingDetailInsert
	@planGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000'
as
	if (not exists(select 1 from ob.SystemSetting where Name = 'OB Staffing Detail Report Enabled' and Value = '1')) begin
		return
	end

	--get budget to refresh
	declare @budgetid int
	if (@planGUID != '00000000-0000-0000-0000-000000000000') begin
		select @budgetid = DepartmentalBudgetID from ob.viewDimDepartmentalBudget where MemberGUID = @planGUID
		if (@budgetid is null or @budgetid = 0) begin
			return
		end
	end else begin
		set @budgetid = 0
	end
	
	--remove existing data
	if (@budgetid = 0) begin
		truncate table [ob].[FactReportAccountWithStaffingDetail]
		exec dbo.procTableReseedIdentity 'ob', 'FactReportAccountWithStaffingDetail', 1
	end else begin
		delete from [ob].[FactReportAccountWithStaffingDetail] where DepartmentalBudgetID = @budgetid
	end
	
	declare @sql nvarchar(max)
	set @sql = '
		declare @validDataTypeTimeClassFiscalYearCombos table ( DataTypeID tinyint, FiscalYearID int, TimeClassID tinyint, IsCY bit )
		insert into @validDataTypeTimeClassFiscalYearCombos select * from [ob].[viewValidDataTypeTimeClassFiscalYearCombos] 
	'

	--staffing data
	set @sql = @sql + '
		insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total)
		select
			DepartmentalBudgetID 	= vw.DepartmentalBudgetID,
			AccountID 				= vw.AccountID,
			JobCodeID				= vw.JobCodeID,
			PayCodeGroupID			= vw.PayCodeGroupID,
			FiscalYearID 			= vw.FiscalYearID,
			TimeClassID 			= vw.TimeClassID,
			UnitTypeID 				= vw.UnitTypeID,
			Month01 				= vw.Month01,
			Month02 				= vw.Month02,
			Month03 				= vw.Month03,
			Month04 				= vw.Month04,
			Month05 				= vw.Month05,
			Month06 				= vw.Month06,
			Month07 				= vw.Month07,
			Month08 				= vw.Month08,
			Month09 				= vw.Month09,
			Month10 				= vw.Month10,
			Month11 				= vw.Month11,
			Month12 				= vw.Month12,
			YTD 					= cmb.IsCY*vw.YTD,
			Total 					= vw.Total
		from 
			[ob].[viewReportStaffingtoGLAccount] vw
			inner join @validDataTypeTimeClassFiscalYearCombos cmb on vw.TimeClassID=cmb.TimeClassID and vw.DataTypeID=cmb.DataTypeID and vw.FiscalYearID=cmb.FiscalYearID
			inner join [clientob].[FactAccount] fct with (readuncommitted)
				on vw.DepartmentalBudgetID	= fct.DepartmentalBudgetID
				and vw.AccountID 			= fct.AccountID
				and vw.FiscalYearID 		= fct.FiscalYearID
				and vw.TimeClassID 			= fct.TimeClassID
				and vw.UnitTypeID 			= fct.UnitTypeID
				and vw.DataTypeID 			= fct.DataTypeID
	'
	if (@budgetid != 0) begin set @sql = @sql + ' where vw.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end
	set @sql = @sql + ' option (recompile);'

	--non-staffing account data
	set @sql = @sql + '
		insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total)
		select
			DepartmentalBudgetID	= fct.DepartmentalBudgetID, 
			AccountID				= fct.AccountID, 
			JobCodeID				= 0,
			PayCodeGroupID			= 0,
			FiscalYearID 			= fct.FiscalYearID, 
			TimeClassID 			= fct.TimeClassID, 
			UnitTypeID 				= fct.UnitTypeID, 
			Month01 				= fct.Month01,
			Month02 				= fct.Month02,
			Month03 				= fct.Month03,
			Month04 				= fct.Month04,
			Month05 				= fct.Month05,
			Month06 				= fct.Month06,
			Month07 				= fct.Month07,
			Month08 				= fct.Month08,
			Month09 				= fct.Month09,
			Month10 				= fct.Month10,
			Month11 				= fct.Month11,
			Month12 				= fct.Month12,
			YTD 					= cmb.IsCY*fct.YTD,
			Total 					= fct.Total
		from 
			[clientob].[FactAccount] fct with (readuncommitted)
			inner join @validDataTypeTimeClassFiscalYearCombos cmb on fct.TimeClassID=cmb.TimeClassID and fct.DataTypeID=cmb.DataTypeID and fct.FiscalYearID=cmb.FiscalYearID
		where 
			not exists
			(
				select 1
				from [ob].[FactReportAccountWithStaffingDetail] vw
				where 1=1
					and fct.DepartmentalBudgetID 	= vw.DepartmentalBudgetID
					and fct.AccountID 				= vw.AccountID
					and fct.FiscalYearID 			= vw.FiscalYearID
					and fct.TimeClassID 			= vw.TimeClassID
					and fct.UnitTypeID 				= vw.UnitTypeID
			)
	'
	if (@budgetid != 0) begin set @sql = @sql + ' and fct.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end
	set @sql = @sql + ' option (recompile);'

	--GL data historical input data discrepancy
	set @sql = @sql + '
		insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total)
		select
			DepartmentalBudgetID 	= fct.DepartmentalBudgetID,
			AccountID 				= fct.AccountID,
			JobCodeID				= 0,
			PayCodeGroupID			= 0,
			FiscalYearID 			= fct.FiscalYearID,
			TimeClassID 			= fct.TimeClassID,
			UnitTypeID 				= fct.UnitTypeID,
			Month01 				= max(fct.Month01) - sum(vw.Month01),
			Month02 				= max(fct.Month02) - sum(vw.Month02),
			Month03 				= max(fct.Month03) - sum(vw.Month03),
			Month04 				= max(fct.Month04) - sum(vw.Month04),
			Month05 				= max(fct.Month05) - sum(vw.Month05),
			Month06 				= max(fct.Month06) - sum(vw.Month06),
			Month07 				= max(fct.Month07) - sum(vw.Month07),
			Month08 				= max(fct.Month08) - sum(vw.Month08),
			Month09 				= max(fct.Month09) - sum(vw.Month09),
			Month10 				= max(fct.Month10) - sum(vw.Month10),
			Month11 				= max(fct.Month11) - sum(vw.Month11),
			Month12 				= max(fct.Month12) - sum(vw.Month12),
			YTD 					= max(cast(cmb.IsCY as int))*(max(fct.YTD ) - sum(vw.YTD)),
			Total 					= max(fct.Total ) - sum(vw.Total)
		from 
			[clientob].[FactAccount] fct with (readuncommitted)
			inner join @validDataTypeTimeClassFiscalYearCombos cmb on fct.TimeClassID=cmb.TimeClassID and fct.DataTypeID=cmb.DataTypeID and fct.FiscalYearID=cmb.FiscalYearID
			inner join [ob].[viewReportStaffingtoGLAccount] vw
				on fct.DepartmentalBudgetID = vw.DepartmentalBudgetID
				and fct.AccountID 			= vw.AccountID
				and fct.FiscalYearID 		= vw.FiscalYearID
				and fct.TimeClassID 		= vw.TimeClassID
				and fct.UnitTypeID 			= vw.UnitTypeID
				and fct.DataTypeID			= vw.DataTypeID
		where 
			fct.DataTypeID in(4, 12)'
		if (@budgetid != 0) begin set @sql = @sql + ' and fct.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end
		set @sql = @sql + '
		group by
			fct.DepartmentalBudgetID,
			fct.AccountID,
			fct.FiscalYearID,
			fct.TimeClassID,
			fct.UnitTypeID
		having
			max(fct.Total) <> SUM(vw.Total)
		option (recompile)
	'

	exec(@sql)
GO


---------------------------------------------

-- ob.procFactReportFinancialStatementInsert
CREATE PROC [ob].[procFactReportFinancialStatementInsert]
	@planGUID uniqueidentifier
WITH RECOMPILE
AS
	set nocount on

	declare @budgetid int
	if (@planGUID != '00000000-0000-0000-0000-000000000000') begin
		select @budgetid = DepartmentalBudgetID from ob.viewDimDepartmentalBudget where MemberGUID = @planGUID
		if (@budgetid is null or @budgetid = 0) begin
			return
		end
	end else begin
		exec [ob].[procFactReportFinancialStatementInsertAll]
		return
	end

	delete from [ob].[FactReportFinancialStatement] where DepartmentalBudgetID = @budgetid

	declare @sql nvarchar(max)
	set @sql = '
		-- GL Dollars 
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			data.AccountID,
			acc.OBDollarsFinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			0 as SnapshotID -- current snapshot
		from
			clientob.FactAccount data with (readuncommitted)
			inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID=''Dollars''
		where
			acc.IsGlobal=0
			{0}
		option (recompile);

		-- Statistics
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			data.AccountID,
			acc.OBUnitsFinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			0 as SnapshotID -- current snapshot
		from
			clientob.FactAccount data with (readuncommitted)
			inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID<>''Dollars''
		where
			not exists (select 1 from [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted)
				inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on fct.OBGlobalStatisticID=gs.OBGlobalStatisticID
				where fct.IsReportable=0 and gs.AccountID=acc.AccountID and fct.DepartmentID=DD.DepartmentID
			)
			{0}
		option (recompile);
	
		-- Hard Referenced Data
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			0 as AccountID,
			data.FinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			0 as SnapshotID -- current snapshot
		from
			[clientob].[FactReportingMonthly] data with (readuncommitted)
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on data.FinancialReportingID=fr.FinancialReportingID
		where
			fr.Statement=''Stats''
			{0}
		option (recompile);
	
		-- GL Dollars (snapshot data)
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			data.AccountID,
			acc.OBDollarsFinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			data.OBSnapshotID as SnapshotID
		from
			ob.FactAccountSnapshot data with (readuncommitted)
			inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID=''Dollars''
		where
			acc.IsGlobal=0
			{0}
		option (recompile);
	
		-- Statistics (snapshot data)
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			data.AccountID,
			acc.OBUnitsFinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			data.OBSnapshotID as SnapshotID
		from
			ob.FactAccountSnapshot data with (readuncommitted)
			inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID<>''Dollars''
		where
			not exists (select 1 from [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted)
				inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on fct.OBGlobalStatisticID=gs.OBGlobalStatisticID
				where fct.IsReportable=0 and gs.AccountID=acc.AccountID and fct.DepartmentID=DD.DepartmentID
			)
			{0}
		option (recompile);
	
		-- Hard Referenced Data (snapshot data)
		insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID)
		select
			data.DepartmentalBudgetID,
			DD.DepartmentID,
			0 as AccountID,
			data.FinancialReportingID as FinancialReportingID,
			FiscalYearID,
			TimeClassID,
			Month01,
			Month02,
			Month03,
			Month04,
			Month05,
			Month06,
			Month07,
			Month08,
			Month09,
			Month10,
			Month11,
			Month12,
			YTD,
			Yearly,
			Total,
			data.OBSnapshotID as SnapshotID
		from
			[ob].[FactReportingMonthlySnapshot] data with (readuncommitted)
			inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID
			inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID
			inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on data.FinancialReportingID=fr.FinancialReportingID
		where
			fr.Statement=''Stats''
			{0}
		option (recompile);
	'
	select @sql = replace(@sql, '{0}', 'and DB.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)))
	exec(@sql)

	delete from [ob].[FactReportFinancialStatement_Pivoted] where DepartmentalBudgetID = @budgetid

	set @sql = '
		insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID)
	    SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, source.Total, 0 as Yearly, 0 as YTD, 0 as Amount, source.Total as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID
		FROM [ob].[FactReportFinancialStatement] source with (readuncommitted)
		WHERE source.Total != 0 {0}

		insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID)
		SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, source.Yearly, 0 as YTD, 0 as Amount, source.Yearly as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID
		FROM [ob].[FactReportFinancialStatement] source with (readuncommitted)
		WHERE source.Yearly != 0 {0}

		insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID)
		SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, 0 as Yearly, source.YTD, 0 as Amount, source.YTD as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID
		FROM [ob].[FactReportFinancialStatement] source with (readuncommitted)
		WHERE source.YTD != 0 {0}

		insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID)
		SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, 0 as Yearly, 0 as YTD, source.Amount, source.Amount as MaxValue, source.YTD as MaxValueYTD, fm.FiscalMonthID
		FROM 
			(select * from [ob].[FactReportFinancialStatement] with (readuncommitted)) p 
			unpivot (Amount for MonthColumnName in (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as source
			inner join fw.DimFiscalMonth fm with (readuncommitted) on source.MonthColumnName = fm.MonthColumnName 
			where (source.Amount != 0 or source.YTD != 0) {0}
	'
	select @sql = replace(@sql, '{0}', 'and source.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)))
	exec(@sql)
GO


---------------------------------------------

-- ob.procFactReportFinancialStatementInsertAll
CREATE PROC [ob].[procFactReportFinancialStatementInsertAll]
	@isContinueFromLastRun bit = 0
WITH RECOMPILE
AS
	set nocount on

	if (@isContinueFromLastRun = 0) begin
		truncate table [ob].[FactReportFinancialStatement]
		exec dbo.procTableReseedIdentity 'ob', 'FactReportFinancialStatement', 1

		truncate table [ob].[FactReportFinancialStatement_Pivoted]
		exec dbo.procTableReseedIdentity 'ob', 'FactReportFinancialStatement_Pivoted', 1
	end
	
	declare @memberGUID uniqueidentifier
	declare crsBudgets cursor fast_forward for select b.MemberGUID from ob.viewDimDepartmentalBudget b where not exists(select 1 from ob.FactReportFinancialStatement fs where fs.DepartmentalBudgetID = b.DepartmentalBudgetID)
	open crsBudgets
	fetch next from crsBudgets into @memberGUID
	while (@@FETCH_STATUS = 0) begin
		exec [ob].[procFactReportFinancialStatementInsert] @memberGUID
		fetch next from crsBudgets into @memberGUID
	end
	close crsBudgets
	deallocate crsBudgets
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_ChargeCode
create proc [ob].[procFinalizeBudget_SampleToInt_ChargeCode]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies Charge Code Budget Data into 'int' tables
** Last Modified: 2016-03-22
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date		Author	WI		Description
**	
*********************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample Charge Code budget data into int tables'
			else 'Sample Charge Code budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Charge Code data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Charge Code data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactCDM]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactCDM] (
	DepartmentID,
	DepartmentCode,
	ChargeCodeID,
	ChargeCode,
	FiscalYearID,
	FiscalYearCode,
	TimeClassID,
	TimeClassCode,
	FiscalMonthID,
	FiscalMonthCode,
	PatientClassID,
	PatientClassCode,
	ServiceLineID,
	ServiceLine,
	AgeCohortID,
	AgeCohort,
	MedicalSurgicalID,
	MedSurg,
	UnitTypeID,
	UnitType,
	Value,
	IsDeleted,
	HistoryItemGUID)
SELECT
	DEP.DepartmentID,
	DEP.DepartmentCode,
	CC.ChargeCodeID,
	CC.ChargeCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID AS FiscalYearCode,
	TC.TimeClassID,
	TC.TimeClassCode,
	FM.FiscalMonthID,
	FM.FiscalMonthCode,
	PAT.PatientClassID,
	PAT.Code as [PatientClassCode],
	''0'' as ServiceLineID,
	'''' as ServiceLine,
	''0'' as AgeCohortID,
	'''' as AgeCohort,
	''0'' as MedicalSurgicalID,
	'''' as MedSurg,
	UT.UnitTypeID,
	UT.Name as [UnitType],
	Value,
	''0'' as IsDeleted,
	'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactCDM] fac
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
INNER JOIN [ob].[DimDepartmentalBudget] Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = Budget.DepartmentID 
INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_GL
CREATE proc [ob].[procFinalizeBudget_SampleToInt_GL]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies GL Budget Data into 'int' tables
** Last Modified: 2016-12-12
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date			Author		WI			Description
**	1		2016-12-12	srk			B-13006	Added section to transfer GL Budget Hours
*********************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample GL budget data into int tables'
			else 'Sample GL budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- GL Dollars
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- GL Dollars
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactGL]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2
	
-- Insert Budget data
INSERT INTO [int].[FactGL]
(
	[DepartmentID],
	[DepartmentCode],
	[AccountID],
	[AccountCode],
	[FiscalYearID],
	[FiscalYearCode],
	[TimeClassID],
	[TimeClassCode],
	[FiscalMonthID],
	[FiscalMonthCode],
	[Value],
	[IsDeleted],
	[HistoryItemGUID]
)
SELECT
	dep.DepartmentID,
	dep.DepartmentCode,
	acc.AccountID,
	acc.AccountCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID as FiscalYearCode,
	tc.TimeClassID,
	tc.TimeClassCode,
	fm.FiscalMonthID,
	fm.FiscalMonthCode,
	acc.inversion*Value as Value,
	''0'' as IsDeleted,
	'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactAccount] fac
		WHERE fac.UnitTypeID = 34 --Dollars only
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID 
	INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

--------------------------------------------------------------------------------------------------
-- Department Stats - Volumes
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Department Stats
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE FS
FROM [int].[FactStatistic] FS
INNER JOIN [fw].[DimAccount] DA ON FS.[AccountID] = DA.[AccountID]
WHERE 1=1
	and FS.[FiscalYearID] = '
+ cast(@year as nvarchar(4))
+ ' and FS.[TimeClassID] = 2
	and DA.[OBStatUnitTypeID] = 140 -- Volumes Only
-- Insert Budget data
INSERT INTO [int].[FactStatistic]
(
	[DepartmentID],
	[DepartmentCode],
	[AccountID],
	[AccountCode],
	[FiscalYearID],
	[FiscalYearCode],
	[TimeClassID],
	[TimeClassCode],
	[FiscalMonthID],
	[FiscalMonthCode],
	[Value],
	[IsDeleted],
	[HistoryItemGUID]
)
SELECT
	dep.DepartmentID,
	dep.DepartmentCode,
	acc.AccountID,
	acc.AccountCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID as FiscalYearCode,
	tc.TimeClassID,
	tc.TimeClassCode,
	fm.FiscalMonthID,
	fm.FiscalMonthCode,
	acc.inversion*Value as Value,
	''0'' as IsDeleted,
	'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactAccount] fac
		WHERE fac.UnitTypeID = 140 --Volumes Only
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID 
	INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))

	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

--------------------------------------------------------------------------------------------------
-- Department Stats - GL Hours
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Department Stats
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE FS
FROM [int].[FactStatistic] FS
INNER JOIN [fw].[DimAccount] DA ON FS.[AccountID] = DA.[AccountID]
WHERE 1=1
	and FS.[FiscalYearID] = '
+ cast(@year as nvarchar(4))
+ ' and FS.[TimeClassID] = 2
	and DA.[OBStatUnitTypeID] = 51 -- Hours Only

-- Insert Budget data
INSERT INTO [int].[FactStatistic]
(
	[DepartmentID],
	[DepartmentCode],
	[AccountID],
	[AccountCode],
	[FiscalYearID],
	[FiscalYearCode],
	[TimeClassID],
	[TimeClassCode],
	[FiscalMonthID],
	[FiscalMonthCode],
	[Value],
	[IsDeleted],
	[HistoryItemGUID]
)
SELECT
	dep.DepartmentID,
	dep.DepartmentCode,
	acc.AccountID,
	acc.AccountCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID as FiscalYearCode,
	tc.TimeClassID,
	tc.TimeClassCode,
	fm.FiscalMonthID,
	fm.FiscalMonthCode,
	acc.inversion*Value as Value,
	''0'' as IsDeleted,
	'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactAccount] fac
		WHERE fac.UnitTypeID = 51 --Hours only
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID 
	INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))

	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end
		
--------------------------------------------------------------------------------------------------
-- Global Stats
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Insert Global Stats
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactGlobalStatistics]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactGlobalStatistics] 
(
	EntityID,
	EntityCode,
	DepartmentID,
	DepartmentCode,
	AccountID,
	AccountCode,
	FiscalYearID,
	FiscalYearCode,
	TimeClassID,
	TimeClassCode,
	FiscalMonthID,
	FiscalMonthCode,
	Value,
	IsDeleted,
	HistoryItemGUID
)
SELECT
	ent.EntityID,
	ent.Code as [EntityCode],
	''0'' as DepartmentID,
	''0'' as DepartmentCode,
	acc.AccountID,
	acc.AccountCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID as FiscalYearCode,
	tc.TimeClassID,
	tc.TimeClassCode,
	fm.FiscalMonthID,
	fm.FiscalMonthCode,
	acc.inversion*Value as Value,
	''0'' as IsDeleted,
	'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactGlobalStatistics] fac
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN [ob].[DimOBGlobalStatistics] gs on gs.OBGlobalStatisticID = BudgetedData.OBGlobalStatisticID
	INNER JOIN fw.DimAccount acc on acc.AccountID = GS.AccountID 
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = GS.DepartmentID
	INNER JOIN ob.DimOBGlobalStatisticsPlan GSP on GSP.OBGlobalStatisticsPlanID = BudgetedData.OBGlobalStatisticsPlanID
	INNER JOIN fw.DimEntity ent on GSP.EntityID = ent.EntityID
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
WHERE 1=1
	and gs.DepartmentID = 0 
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))

	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_Payroll
CREATE proc [ob].[procFinalizeBudget_SampleToInt_Payroll]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies Staffing Budget Data into 'int' tables
** Last Modified: 2016-03-22
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date		Author		WI		Description
**	1   2/9/2018     sdominsk  D-06820  Change filter in where clause for ut.UnitTypeID (added ''147'',''52'').
*********************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample Payroll budget data into int tables'
			else 'Sample Payroll budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Staffing data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Staffing data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactStaffing]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactStaffing] (
	DepartmentID 
	, DepartmentCode 
	, JobCodeID 
	, JobCode 
	, PayCodeID 
	, PayCode 
	, FiscalYearID 
	, FiscalYearCode
	, TimeClassID
	, TimeClassCode
	, UnitTypeID 
	, UnitType
	, FiscalMonthID 
	, FiscalMonthCode
	, Value
	, IsDeleted
	, HistoryItemGUID
	, EmployeeID 
	, EmployeeCode)
SELECT
	dep.DepartmentID 
	, dep.DepartmentCode 
	, jc.JobCodeID 
	, jc.JobCode 
	, pc.PayCodeID 
	, pc.PayCode 
	, BudgetedData.FiscalYearID 
	, BudgetedData.FiscalYearID as FiscalYearCode
	, tc.TimeClassID
	, tc.TimeClassCode
	, case 
		when ut.UnitTypeID = 34
			then 34
		else 51
		end as UnitTypeID
	, case
		when ut.Name =''Dollars''
			then ''Dollars''
		else ''Hours''
		end as UnitType
	, fm.FiscalMonthID 
	, fm.FiscalMonthCode
	, Value as Value
	, ''0'' as IsDeleted
	, '''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
	, ''0'' as EmployeeID 
	, ''0'' as EmployeeCode
FROM (
	SELECT * 
	FROM ( 
		SELECT *
		FROM [clientob].[FactStaffingPC] fac
		) EXPORTDATA   
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = BudgetedData.JobCodeID 
	INNER JOIN [ob].[DimDepartmentalBudget] budget on budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = budget.DepartmentID 
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = BudgetedData.PayCodeGroupID
	INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
	INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
WHERE 1=1
	and ut.UnitTypeID IN (''34'',''146'',''148'',''147'',''52'')
	and BudgetedData.Value <> 0 
	and PCG.PayCodeGroupID<>0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end


end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_Provider
CREATE proc [ob].[procFinalizeBudget_SampleToInt_Provider]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies Provider Budget Data into 'int' tables
** Last Modified: 2016-03-22
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date		Author		WI			Description
**	1		2017-11-22	srk			D-04334		Stamp off Provider Hours instead of FTEs
** 	2		2019-01-10	ljc			B-15790		reverting CID 1. Provider output Hours now mapped 
*********************************************************************************************************/
as
begin

--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample Provider budget data into int tables'
			else 'Sample Provider budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Provider data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Provider data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactImportProvider]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactImportProvider] (
	DepartmentID
	, DepartmentCode
	, ProviderID
	, ProviderCode
	, FiscalYearID
	, FiscalYearCode
	, TimeClassID
	, TimeClassCode
	, FiscalMonthID
	, FiscalMonthCode
	, OBForecastDetailID
	, AccountRollup
	, Value
	, IsDeleted
	, HistoryItemGUID
	)
SELECT
	D.DepartmentID
	, D.DepartmentCode
	, PRO.ProviderID
	, PRO.ProviderCode
	, BudgetedData.FiscalYearID
	, BudgetedData.FiscalYearID as [FiscalYearCode]
	, TC.TimeClassID
	, TC.TimeClassCode
	, FM.FiscalMonthID
	, FM.FiscalMonthCode
	, FD.OBForecastDetailID
	, FD.Name as [AccountRollup]
	, Value
	,''0'' as IsDeleted
	,'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactProvider] fac
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
INNER JOIN [fw].[DimProvider] PRO ON PRO.ProviderID = BudgetedData.ProviderID
INNER JOIN [ob].[DimDepartmentalBudget] P ON P.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = P.DepartmentID
INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_Reimbursement
CREATE proc [ob].[procFinalizeBudget_SampleToInt_Reimbursement]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies Reimbursement Budget Data into 'int' tables
** Last Modified: 2016-03-22
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date		Author	WI		Description
** 	1		2016-11-21	srk	D-04390		Comment out Payor transfer to avoid duplicaton
*********************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample Reimbursement budget data into int tables'
			else 'Sample Reimbursement budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Payor data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Payor data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactOBPayor]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

---- Insert Budget data
--INSERT INTO [int].[FactOBPayor] (
--		OBReimbursementPlanID,
--		ReimbursementPlan,
--		PatientClassID,
--		PatientClassCode,
--		PayorID,
--		PayorCode,
--		FiscalYearID,
--		FiscalYearCode,
--		TimeClassID,
--		TimeClassCode,
--		FiscalMonthID,
--		FiscalMonthCode,
--		OBForecastDetailID,
--		OBForecastDetailCode,
--		CareSettingID,
--		CareSettingCode,
--		Value,
--		IsDeleted,
--		HistoryItemGUID)
--SELECT
--	P.OBReimbursementPlanID,
--	P.Name as ReimbursementPlan,
--	PAT.PatientClassID,
--	PAT.Code as PatientClassCode,
--	PAY.PayorID,
--	PAY.PayorCode,
--	BudgetedData.FiscalYearID,
--	BudgetedData.FiscalYearID as FiscalYearCode,
--	TC.TimeClassID,
--	TC.TimeClassCode,
--	fm.FiscalMonthID,
--	fm.FiscalMonthCode,
--	FD.OBForecastDetailID,
--	FD.Code as OBForecastDetail,
--	C.CareSettingID,
--	C.Code as CareSettingCode,
--	Value
--	,''0'' as IsDeleted
--	,'''
--	+ cast(@higuid as varchar(36))
--	+ ''' as HistoryItemGUID
--FROM (
--	SELECT *
--	FROM (
--	 	SELECT *
--		FROM [clientob].[FactReimbursement] fac
--		) EXPORTDATA 
--	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
--) BudgetedData
--	INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID
--	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID
--	INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID
--	INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID = BudgetedData.PayorID
--	INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID
--	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
--	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
--	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
--WHERE 1=1
--	and BudgetedData.Value <> 0
--	and BudgetedData.TimeClassID = 2
--	and BudgetedData.IsDeleted = 0
--	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
--	
--	if @IsDebugOnly=1
--		begin
--			print(@sql)
--		end
--	else
--		begin
--			exec(@sql)
--		end

--------------------------------------------------------------------------------------------------
-- Payor group data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Payor group data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactOBPayorGroup]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactOBPayorGroup] (
		OBReimbursementPlanID,
		ReimbursementPlan,
		PatientClassID,
		PatientClassCode,
		PayorGroupID,
		PayorGroupCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		FiscalMonthID,
		FiscalMonthCode,
		OBForecastDetailID,
		OBForecastDetailCode,
		CareSettingID,
		CareSettingCode,
		Value,
		IsDeleted,
		HistoryItemGUID)
SELECT
	P.OBReimbursementPlanID,
	P.Name as ReimbursementPlan,
	PAT.PatientClassID,
	PAT.Code as PatientClassCode,
	PAY.PayorGroupID,
	PAY.PayorGroupCode,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID as FiscalYearCode,
	TC.TimeClassID,
	TC.TimeClassCode,
	fm.FiscalMonthID,
	fm.FiscalMonthCode,
	FD.OBForecastDetailID,
	FD.Code as OBForecastDetail,
	C.CareSettingID,
	C.Code as CareSettingCode,
	Value
	,''0'' as IsDeleted
	,'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactReimbursement] fac
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
	INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID
	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID
	INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID
	INNER JOIN [fw].[DimPayorGroup] PAY ON PAY.PayorGroupID = BudgetedData.PayorGroupID
	INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinalizeBudget_SampleToInt_SL
CREATE proc [ob].[procFinalizeBudget_SampleToInt_SL]
	@IsDebugOnly bit = 0
/* ******************************************************************************************************
** Author: Corey Becker
** Create Date: 2016-03-22
** Description: Copies Service Line Budget Data into 'int' tables
** Last Modified: 2016-03-22
** GM Release: 2016.3
*********************************************************************************************************
** Change History
*********************************************************************************************************
**	CID		Date		Author	WI		Description
** 	1		2016-11-21	srk	D-04550		Add DepartmentCode and DepartmentID to the Service Line transfer 	
*********************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = 
		case @IsDebugOnly
			when 1 then 'Debug only - Sample Service Line budget data into int tables'
			else 'Sample Service Line budget data into int tables'
		end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Variable declarations
--------------------------------------------------------------------------------------------------
	declare @year int
	select @year = dbs.Setting+1 
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Service Line data
--------------------------------------------------------------------------------------------------
	SET @sql = '
-- Service Line data
--------------------------------------------------------------------------------------------------
-- Delete Existing
DELETE 
FROM [int].[FactServiceLine]
WHERE 1=1
	and FiscalYearID = '
+ cast(@year as nvarchar(4))
+ ' and TimeClassID = 2

-- Insert Budget data
INSERT INTO [int].[FactServiceLine] (
	EntityID,
	EntityCode,
	DepartmentID,
	DepartmentCode,
	PatientClassID,
	PatientClassCode,
	ServiceLineID,
	ServiceLine,
	AgeCohortID,
	AgeCohort,
	MedicalSurgicalID,
	MedSurg,
	PayorID,
	PayorGroupID,
	FiscalYearID,
	FiscalYearCode,
	TimeClassID,
	TimeClassCode,
	FiscalMonthID,
	FiscalMonthCode,
	OBForecastDetailID,
	ForecastDetail,
	Value,
	IsDeleted,
	HistoryItemGUID)
SELECT
	E.EntityID,
	E.Code as [EntityCode],
	DEPT.DepartmentID,
	DEPT.DepartmentCode,
	PAT.PatientClassID,
	PAT.Code as [PatientClassCode],
	SL.ServiceLineID,
	SL.Code as [ServiceLineCode],
	AGE.AgeCohortID,
	AGE.Code as [AgeCohort],
	MED.MedicalSurgicalID,
	MED.Code as [MedSurg],
	PAY.PayorID,
	PAYG.PayorGroupID,
	BudgetedData.FiscalYearID,
	BudgetedData.FiscalYearID AS FiscalYearCode,
	TC.TimeClassID,
	TC.TimeClassCode,
	FM.FiscalMonthID,
	FM.FiscalMonthCode,
	FD.OBForecastDetailID,
	FD.Code as [ForecastDetail],
	Value
	,''0'' as IsDeleted
	,'''
	+ cast(@higuid as varchar(36))
	+ ''' as HistoryItemGUID
FROM (
	SELECT *
	FROM (
	 	SELECT *
		FROM [clientob].[FactServiceLine] fac
		) EXPORTDATA 
	UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
) BudgetedData
INNER JOIN [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = BudgetedData.ModelingServiceLineID
INNER JOIN [fw].[DimServiceLine] SL ON MSL.ServiceLineID = SL.ServiceLineID
INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = MSL.PatientClassID
INNER JOIN [fw].[DimAgeCohort] AGE ON AGE.AgeCohortID = MSL.AgeCohortID
INNER JOIN [fw].[DimMedicalSurgical] MED ON MED.MedicalSurgicalID = MSL.MedicalSurgicalID
INNER JOIN [ob].[DimOBServiceLinePlan] P ON P.OBServiceLinePlanID = BudgetedData.OBServiceLinePlanID
INNER JOIN [fw].[DimEntity] E on E.EntityID = P.EntityID
	CROSS APPLY 
		(
		SELECT TOP 1 DD.DepartmentCode, DD.DepartmentID 
		from [fw].[DimDepartment] DD 
		where DD.EntityID = E.EntityID
		) DEPT
INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID=0
INNER JOIN [fw].[DimPayorGroup] PAYG ON PAYG.PayorGroupID=0
WHERE 1=1
	and BudgetedData.Value <> 0
	and BudgetedData.TimeClassID = 2
	and BudgetedData.IsDeleted = 0
	and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4))
	
	if @IsDebugOnly=1
		begin
			print(@sql)
		end
	else
		begin
			exec(@sql)
		end

end  --END OF PROCEDURE
GO


---------------------------------------------

-- ob.procFinancialReportingSyncBalFromSP
CREATE proc [ob].[procFinancialReportingSyncBalFromSP]
AS
	--apply renames
	update ob set ob.LineName = sp.LineName, ob.Name = sp.Name, ob.DisplayFormat = sp.DisplayFormat, ob.SortOrder = sp.SortOrder, ob.IsExpense = sp.ConsolidatedIsInverted
	from ob.DimFinancialReporting ob
	inner join sp.DimFinancialReporting sp on sp.FinancialReportingID = ob.ConsolidatedFinancialReportingID
	where ob.Statement = 'Bal'

	--add missing
	declare @startID int
	select @startID = MAX(FinancialReportingID) from ob.DimFinancialReporting
	INSERT INTO ob.DimFinancialReporting (Statement, Section, LineName, IsMappable, ConsolidatedFinancialReportingID, ConsolidatedIsInverted, Name, StatementMappabilityFilterParameter, ConsolidatedFinancialReporting, ConsolidatedFinancialReportingSortOrder, IsRequired, IsVolume, IsFTERollup, IsEditable, DisplayFormat, SortOrder, FinancialReportingID, IsExpense)
	SELECT spf.Statement, spf.Section, spf.LineName, spf.IsMappable, spf.FinancialReportingID, spf.ConsolidatedIsInverted, spf.Name, spf.StatementMappabilityFilterParameter, spf.ConsolidatedFinancialReporting, spf.ConsolidatedFinancialReportingSortOrder, spf.IsRequired, spf.IsVolume, spf.IsFTERollup, spf.IsEditable, spf.DisplayFormat, spf.SortOrder, @startID + spf.FinancialReportingID, spf.ConsolidatedIsInverted
	FROM sp.DimFinancialReporting spf
	WHERE spf.Statement = 'Bal'
	AND not exists(select 1 from ob.DimFinancialReporting ex where ex.ConsolidatedFinancialReportingID = spf.FinancialReportingID)

	--reassign accounts tied to invalid
	update a set a.OBDollarsFinancialReportingID = 0
	FROM ob.DimFinancialReporting obf
	inner join fw.DimAccount a on a.OBDollarsFinancialReportingID = obf.FinancialReportingID
	WHERE obf.Statement = 'Bal'
	AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID);

	update a set a.OBUnitsFinancialReportingID = 0
	FROM ob.DimFinancialReporting obf
	inner join fw.DimAccount a on a.OBUnitsFinancialReportingID = obf.FinancialReportingID
	WHERE obf.Statement = 'Bal'
	AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID);

	--delete invalid
	DELETE obf
	FROM ob.DimFinancialReporting obf
	WHERE obf.Statement = 'Bal'
	AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID)
GO


---------------------------------------------

-- ob.procImplDepartmentBudgetClearAssumptionsAndOutputs
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Deletes all assumptions and output data for the department budget template - NEVER RUN ON LIVE DATABASES
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		11-24-2014	BL		B-03364	Add Clear Non-Reporting to Proc
**
*************************************************************/
CREATE proc ob.procImplDepartmentBudgetClearAssumptionsAndOutputs
	@isExecuting bit = 0
as
if (@isExecuting=1)
begin
declare @dbname nvarchar(1000) = (DB_Name())
/**************  Remove var data *******************/

--Remove data from Fact Account Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountVar', 'clientob'
delete fa
from [clientob].[FactAccountvar] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID


--Remove data from Fact Account Rollup Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountRollupVar', 'clientob'
delete fa
from [clientob].[FactAccountRollupvar] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID


--Remove data from Fact Staffing PC Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob'
delete fs 
from [clientob].[FactStaffingPCVar] fs
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fs.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID


--Remove data from Fact CDM Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactCDMVar', 'clientob'
delete fa
from [clientob].[FactCDMvar] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID

--Remove data from Fact Provider Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProviderVar', 'clientob'
delete fa
from [clientob].[FactProvidervar] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID


/**************  Remove output data *******************/

--Remove output data from Fact Account
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccount', 'clientob'
delete fa 
from [clientob].[FactAccount] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
where DataTypeID=3

--Remove output data from Fact Account Non Reporting
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountNonReporting', 'clientob'
delete fa 
from [clientob].[FactAccountNonReporting] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
where DataTypeID=3

--Remove output data from Fact Staffing PC
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPC', 'clientob'
delete fs
from [clientob].[FactStaffingPC] fs
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fs.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
where DataTypeID=3

--Remove output data from Fact CDM
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactCDM', 'clientob'
delete fa 
from [clientob].[FactCDM] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
where DataTypeID=3

--Remove output data from Fact Provider
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProvider', 'clientob'
delete fa 
from [clientob].[FactProvider] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
where DataTypeID=3

--Remove output data from Fact Reporting Monthly
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReportingMonthly', 'clientob'
delete fa 
from [clientob].[FactReportingMonthly] fa
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID
inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID
inner join [ob].[DimFinancialReporting] fr on fr.FinancialReportingID=fa.FinancialReportingID
where fr.Statement<>'Standards'

/**************  Repopulate data from entity models  *******************/
exec [clientob].[procSampleCDMBudgetYear] 
exec [clientob].[procSampleCDMCurrentYear]
exec [clientob].[procFactGlobalStatisticMappingSample] 
exec [clientob].[procFactReimbursementMappingSample] 

end

RETURN
GO


---------------------------------------------

-- ob.procImplFixInvalidDropDownSelections
/************************************************************
** Author: akowalski
** Create Date: 2014-09-23
** Description: Fixes any text boxes that saved a value of blank that will cause #n/a errors in the model
** Last Modified: 2014-09-23
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE proc ob.procImplFixInvalidDropDownSelections as

--get list of affected plans
select distinct db.MemberGUID as PlanGUID
into #Plans
from [ob].[viewExceptionsDepartmentBudgetInvalidDropdownSelection] e
inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=e.DepartmentalBudgetID


declare @dbname nvarchar(1000) = (DB_Name())

--Accounts
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountVar', 'clientob'

update fct
set TextValue_Formula='d'
from clientob.factaccountvar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''


-- Job Codes
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob'
update fct
set TextValue_Formula='d'
from clientob.FactStaffingPCVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''
and EmployeeID=0



-- Providers
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProviderVar', 'clientob'
update fct
set TextValue_Formula='d'
from clientob.FactProviderVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''


-- Employees
update fct
set TextValue_Formula='d'
from clientob.FactStaffingPCVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join fw.DimEmployee DIM with (readuncommitted) on fct.EmployeeID = DIM.EmployeeID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''
and DIM.EmployeeID<>0


-- Global Methods
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountRollupVar', 'clientob'
update fct
set TextValue_Formula='d'
from clientob.FactAccountRollupVar fct with (readuncommitted)
inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID
inner join ob.DimFinancialReporting DIM with (readuncommitted) on fct.FinancialReportingID=DIM.FinancialReportingID
where fct.UnitTypeID=141
and TextValue_Formula='x'
and TextValue=''

-- invalidatae workbook caches for affected plans
DECLARE guidlist CURSOR FOR 
	select planguid from #Plans

open guidlist

declare @sqli varchar(max)
	DECLARE @planguid nvarchar(256)
FETCH NEXT FROM guidlist
	INTO @planguid
WHILE (@@FETCH_STATUS = 0) 
	BEGIN
		SET @sqli = 'exec [dbo].[procInvalidateModelWorkbookCache] @entityguid = ''' + @planguid + ''', @istemplate = 0,@source=''ob.procImplFixInvalidDropDownSelections'''
		exec(@sqli)
		FETCH NEXT FROM guidlist INTO @planguid
	END
CLOSE guidlist
DEALLOCATE guidlist

RETURN
GO


---------------------------------------------

-- ob.procImplGlobalStatsClearAssumptionsAndOutputs
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Deletes all assumptions and output data for the global stats template - NEVER RUN ON LIVE DATABASES
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create proc ob.procImplGlobalStatsClearAssumptionsAndOutputs
	@isExecuting bit = 0
as
if (@isExecuting=1)
begin
declare @dbname nvarchar(1000) = (DB_Name())
/**************  Remove var data *******************/

--Remove data from Fact GlobalStatistics Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatisticsVar', 'clientob'
delete fa
from [clientob].[FactGlobalStatisticsVar] fa
inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID

/**************  Remove output data *******************/

--Remove output data from Fact Account
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatistics', 'clientob'
delete fa 
from [clientob].[FactGlobalStatistics] fa
inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID
where DataTypeID=3

end

RETURN
GO


---------------------------------------------

-- ob.procImplReimbursementClearAssumptionsAndOutputs
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Deletes all assumptions and output data for the reimbursement template - NEVER RUN ON LIVE DATABASES
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2014-11-24	bl		b-03364	Add Fact ReimbAcct and ReimbAcctNonReporting
**
*************************************************************/
CREATE proc ob.procImplReimbursementClearAssumptionsAndOutputs
	@isExecuting bit = 0
as
if (@isExecuting=1)
begin
declare @dbname nvarchar(1000) = (DB_Name())
/**************  Remove var data *******************/

--Remove data from Fact Reimbursement Account Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccountVar', 'clientob'
delete fa
from [clientob].[FactReimbursementAccountVar] fa
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID

--Remove data from Fact Reimbursement Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementVar', 'clientob'
delete fa
from [clientob].[FactReimbursementVar] fa
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID

/**************  Remove output data *******************/

--Remove output data from Fact Reimbursement
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursement', 'clientob'
delete fa 
from [clientob].[FactReimbursement] fa
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID
where DataTypeID=3

--Remove output data from Fact Reimbursement Account
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursement', 'clientob'
delete fa 
from [clientob].[FactReimbursementAccount] fa
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID
where DataTypeID=3

--Remove output data from Fact Reimbursement Account NonReporting
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccountNonReporting', 'clientob'
delete fa 
from [clientob].[FactReimbursementAccountNonReporting] fa
inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID
where DataTypeID=3


end

RETURN
GO


---------------------------------------------

-- ob.procImplServiceLineClearAssumptionsAndOutputs
/************************************************************
** Author: akowalski
** Create Date: 2014-08-27
** Description: Deletes all assumptions and output data for the service line template - NEVER RUN ON LIVE DATABASES
** Last Modified: 2014-08-27
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/
create proc ob.procImplServiceLineClearAssumptionsAndOutputs
	@isExecuting bit = 0
as
if (@isExecuting=1)
begin
declare @dbname nvarchar(1000) = (DB_Name())
/**************  Remove var data *******************/

--Remove data from Fact Service Line Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineVar', 'clientob'
delete fa
from [clientob].[FactServiceLineVar] fa
inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID

--Remove data from Fact Service Line Rollup Var
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineRollupVar', 'clientob'
delete fa
from [clientob].[FactServiceLineRollupVar] fa
inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID

/**************  Remove output data *******************/

--Remove output data from Fact Service Line
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLine', 'clientob'
delete fa 
from [clientob].[FactServiceLine] fa
inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID
where DataTypeID=3

end

RETURN
GO


---------------------------------------------

-- ob.procLockBudgetModels
CREATE PROCEDURE [ob].[procLockBudgetModels]
	@planGUIDs [dbo].[SqlGuidListTableType] READONLY,
	@userGroupGUID UNIQUEIDENTIFIER
AS
BEGIN
	DECLARE @writeDenyRoleID INT = (select RoleID from UserRole where GlobalID = 'OB - Write Deny')
	
	INSERT INTO [dbo].[S3RoleAssignment] (LootGroupID, RoleID, IdentityGUID)
	SELECT CachedLootID, @writeDenyRoleID, @userGroupGUID
	FROM @planGUIDs
	INNER JOIN [dbo].[XPlan] 
		ON PlanGUID = value
	WHERE CachedLootID NOT IN (
			SELECT LootGroupID
			FROM [dbo].[S3RoleAssignment] ra
			WHERE RoleID = @writeDenyRoleID 
				AND IdentityGUID = @userGroupGUID
		)
END
GO


---------------------------------------------

-- ob.procMissingJobCodeWageRates_Update
create proc [ob].[procMissingJobCodeWageRates_Update] 
	@planGUIDList nvarchar(max)='',
	@IsDebugOnly bit = 0
/************************************************************************************************************************
** Author: cbecker
** Create Date: 2015-12-02
** Description: Checks for missing wage rates and sets equal to entity or system average
** Last Modified: 2015-12-02
** GM Release: 2016.1.1
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
**	CID		Date		Author	WI			Description
**	00		0000-00-00	xxx		x-00000		xx xx
*************************************************************************************************************************/
as
begin
	set nocount on

--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @higuid uniqueidentifier
	exec procLogScript 'Update missing job code wage rates' , @higuid output
	print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- Backup
--------------------------------------------------------------------------------------------------
--declare @dbname nvarchar(1000) = (DB_Name())
--exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob'

--------------------------------------------------------------------------------------------------
-- Declare variables
--------------------------------------------------------------------------------------------------
	declare @FiscalYearID int
	select @FiscalYearID = cast(Setting as int)
	from [dbo].[DBSetting]
	where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62'

	declare @RegPCG int
	select @RegPCG = PayCodeGroupID
	from [fw].[DimPayCodeGroup]
	where 1=1
		and ProductiveClassID = 3 
		and SortOrder=(select min(sortorder) from [fw].[DimPayCodeGroup] where ProductiveClassID=3)

--------------------------------------------------------------------------------------------------
-- Populate Pay Code Group temp table
--------------------------------------------------------------------------------------------------
	Create Table #PayCodeGroups(PayCodeGroupID int, ProductiveClassID int, PayCodeGroupID2 int)

	insert into #PayCodeGroups(PayCodeGroupID, ProductiveClassID, PayCodeGroupID2)
	select 
		PayCodeGroupID, 
		ProductiveClassID,
		PayCodeGroupID2 	= 	case pcg.ProductiveClassID
									when 3 then @RegPCG
									else pcg.PayCodeGroupID
								end
	from [fw].[DimPayCodeGroup] pcg
	where ProductiveClassID in (3, 5)

--------------------------------------------------------------------------------------------------
-- Populate plans temp table
--------------------------------------------------------------------------------------------------
	Create Table #Plans(DepartmentalBudgetID int)

	if (len(@planGUIDList) = 0) 
		begin
			-- if no plans provided, we will update job codes for all plans
			insert into #Plans(DepartmentalBudgetID)
			select DepartmentalBudgetID 
			from ob.DimDepartmentalBudget 
		end
	else
		begin
			-- if plans are provided, we will only update job codes in specified plans
			insert into #Plans(DepartmentalBudgetID)
			select
				plandim.DepartmentalBudgetID
			from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') planguids
				inner join ob.DimDepartmentalBudget plandim 
					on planguids.guid = plandim.MemberGUID
		end

--------------------------------------------------------------------------------------------------
-- Populate job codes temp table
--------------------------------------------------------------------------------------------------
	create Table #JobCodes(EntityID int, DepartmentalBudgetID int, PayCodeGroupID int, JobCodeID int, Total money)

	insert into #JobCodes (EntityID, DepartmentalBudgetID, PayCodeGroupID, JobCodeID, Total)
		select distinct
			db.EntityID,
			fct.DepartmentalBudgetID,
			PayCodeGroupID2,
			fct.JobCodeID,
			sum(fct.Total)
		from [clientob].[FactStaffingPC] fct with (readuncommitted)
			inner join #Plans pl
				on fct.DepartmentalBudgetID	=	pl.DepartmentalBudgetID
			inner join [ob].[DimDepartmentalBudget] db
				on pl.DepartmentalBudgetID	=	db.DepartmentalBudgetID
			inner join #PayCodeGroups pcg
				on fct.PayCodeGroupID		=	pcg.PayCodeGroupID
		where 1=1
			and fct.UnitTypeID	= 34
			and fct.TimeClassID	= 2
			and fct.DataTypeID	= 3
			and fct.FiscalYearID = (@FiscalYearID+1)
			and (fct.Total = 0 or pcg.ProductiveClassID = 3)
		group by
			db.EntityID,
			fct.DepartmentalBudgetID,
			pcg.PayCodeGroupID2,
			fct.JobCodeID
		having
			sum(fct.Total) = 0

--------------------------------------------------------------------------------------------------
-- Populate entity average wage temp table
--------------------------------------------------------------------------------------------------
	create table #EntityAvg (Row int, EntityID int, JobCodeID int, FiscalYearID int, SortOrder int, PayCodeGroupID int, Dollars money, Hours money, Wage money)

	insert into #EntityAvg (Row, EntityID, JobCodeID, FiscalYearID, SortOrder, PayCodeGroupID, Dollars, Hours, Wage)
		select
			Row				=	ROW_NUMBER()
									OVER
									(
										partition by
											jc.EntityID,
											pc1.JobCodeID,
											pc1.PayCodeGroupID,
											pc1.FiscalYearID
										order by
											jc.EntityID,
											pc1.JobCodeID,
											pc1.PayCodeGroupID,
											pc1.FiscalYearID desc,
											fm.SortOrder desc
									),
		    EntityID		=	jc.EntityID,
		    JobCodeID		=	pc1.JobCodeID,
		    FiscalYearID	=	pc1.FiscalYearID,
		    SortOrder		=	fm.SortOrder,
			PayCodeGroupID	=	case pc1.PayCodeGroupID 
									when @RegPCG then 0 
									else pc1.PayCodeGroupID 
								end,
			Dollars			=	sum(pc1.Value),
			Hours			=	nullif(sum(pc2.Value),0),
		    Wage			=	coalesce(sum(pc1.Value)/nullif(sum(pc2.Value),0),0)
		from [ob].[viewFactStaffingPCUnpivoted] pc1
			inner join #JobCodes jc
				on pc1.JobCodeID			=	jc.JobCodeID
				--and pc1.DepartmentalBudgetID=	jc.DepartmentalBudgetID
				and pc1.PayCodeGroupID		=	jc.PayCodeGroupID
			inner join [ob].[viewFactStaffingPCUnpivoted] pc2 
				on pc1.DepartmentalBudgetID	=	pc2.DepartmentalBudgetID
			    and pc1.PayCodeGroupID		=	pc2.PayCodeGroupID
			    and pc1.JobCodeID			=	pc2.JobCodeID
			    and pc1.FiscalYearID		=	pc2.FiscalYearID
			    and pc1.TimeClassID			=	pc2.TimeClassID
			    and pc1.DataTypeID			=	pc2.DataTypeID
			    and pc1.FiscalMonthID		=	pc2.FiscalMonthID
			inner join [fw].[DimFiscalMonth] fm
				on pc1.FiscalMonthID		=	fm.FiscalMonthID
		where 1=1
		    and pc1.UnitTypeID		=	34
		    and pc1.Value			<>	0
		    and pc2.Value			<>	0
			and pc1.TimeClassID		=	12
			and pc1.DataTypeID		=	3
			and pc1.FiscalYearID	=	@FiscalYearID
			and pc2.UnitTypeID		in	(147, 148)
		group by
			jc.EntityID,
			pc1.JobCodeID,
			pc1.FiscalYearID,
			fm.SortOrder,
			pc1.PayCodeGroupID

--------------------------------------------------------------------------------------------------
-- Populate system average wage temp table
--------------------------------------------------------------------------------------------------
	create table #SystemAvg (JobCodeID int, PayCodeGroupID int, Wage money)

	insert into #SystemAvg (JobCodeID, PayCodeGroupID, Wage)
		select 
			JobCodeID		=	ea.JobCodeID,
			PayCodeGroupID	=	ea.PayCodeGroupID,
			Wage			=	coalesce(sum(ea.Dollars)/nullif(sum(ea.Hours),0),0)
		from #EntityAvg ea
		where 1=1
			and ea.Row = 1
		group by
			JobCodeID,
			PayCodeGroupID

--------------------------------------------------------------------------------------------------
-- Update wage rate annual adjustment
--------------------------------------------------------------------------------------------------
	if (@IsDebugOnly = 1)
		begin
			select distinct
				Amount				=	coalesce(ea.Wage, sa.Wage, 0),
				Amount_Formula		=	'x',
				HistoryItemGUID		=	@higuid,
				JobCodeID			=	fct.JobCodeID,
				PayCodeGroupID		=	fct.PayCodeGroupID,
				DepartmentalBudgetID=	fct.DepartmentalBudgetID
			from [clientob].[FactStaffingPCVar] fct
				inner join #JobCodes jc
					on fct.DepartmentalBudgetID	=	jc.DepartmentalBudgetID
				inner join #SystemAvg sa
					on fct.JobCodeID			=	sa.JobCodeID
					and fct.PayCodeGroupID		=	sa.PayCodeGroupID
				left join #EntityAvg ea
					on jc.EntityID				=	ea.EntityID
					and fct.JobCodeID			=	ea.JobCodeID
					and fct.PayCodeGroupID		=	ea.PayCodeGroupID
			where 1=1
				and ea.Row				=	1
				and fct.TimeClassID		=	2
				and fct.UnitTypeID		=	159
				and fct.FiscalMonthID	=	0
				and fct.AssumptionID	=	18
				and fct.FiscalYearID	=	(@FiscalYearID+1)

		end
	else
		begin
			update fct
			set 
				Amount			=	coalesce(ea.Wage, sa.Wage, 0),
				Amount_Formula	=	'x',
				HistoryItemGUID	=	@higuid
			from [clientob].[FactStaffingPCVar] fct
				inner join #JobCodes jc
					on fct.DepartmentalBudgetID	=	jc.DepartmentalBudgetID
				inner join #SystemAvg sa
					on fct.JobCodeID			=	sa.JobCodeID
					and fct.PayCodeGroupID		=	sa.PayCodeGroupID
				left join #EntityAvg ea
					on jc.EntityID				=	ea.EntityID
					and fct.JobCodeID			=	ea.JobCodeID
					and fct.PayCodeGroupID		=	ea.PayCodeGroupID
			where 1=1
				and ea.Row				=	1
				and fct.TimeClassID		=	2
				and fct.UnitTypeID		=	159
				and fct.FiscalMonthID	=	0
				and fct.AssumptionID	=	18
				and fct.FiscalYearID	=	(@FiscalYearID+1)
		end

--------------------------------------------------------------------------------------------------
-- Clean-up
--------------------------------------------------------------------------------------------------

--disable cache for plans
	if (@planGUIDList = '') begin
		exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '05512126-3EB6-4DA4-AF6E-BC2BC2724B8B', 'procMissingJobCodeWageRates_Update'
	end else begin
		declare @invalidateWhere nvarchar(max)
		set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @planGUIDList + ''','',''))'
		exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'procMissingJobCodeWageRates_Update'
	end

	drop table #Plans
	drop table #JobCodes
	drop table #EntityAvg
	drop table #SystemAvg

end
GO


---------------------------------------------

-- ob.procOBSPSLForecastYr1VoltoOBBaseline
create proc [ob].[procOBSPSLForecastYr1VoltoOBBaseline]
	@planGUIDList nvarchar(max)='',
	@IsDebugOnly bit = 0
/************************************************************************************************************************
** Author: cbecker
** Create Date: 2016-04-05
** Description: B-11790 transfer service line volumes from strategic planning to the OB Service line model
** Last Modified: 2016-04-05
** GM Release: 2016.2.1
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
**	CID		Date		Author	WI			Description
**	
*************************************************************************************************************************/
as
begin
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	declare @logdesc nvarchar(100)
	select @logdesc = case @IsDebugOnly
						when 1 then 'Debug only - Transfer SP service line volumes from SP forecast year 1 to OB SL baseline'
						else 'Transfer SP service line volumes from SP forecast year 1 to OB SL baseline'
						end
	
	declare @higuid uniqueidentifier
	exec procLogScript @logdesc, @higuid output

	print N'select * from [dbo].[HistoryItem] where HISTORYITEMGUID='''
		+cast(@higuid as varchar(36))
		+N''''

--------------------------------------------------------------------------------------------------
-- Declare variables
--------------------------------------------------------------------------------------------------
	declare @budgetyear int
	select @budgetyear = dbs.Setting+1
	from [dbo].[DBSetting] dbs
	where dbs.Name = 'OB_Current_Year'
	
	declare @sql nvarchar(max) = ''

--------------------------------------------------------------------------------------------------
-- Populate plans temp table
--------------------------------------------------------------------------------------------------
	Create Table #Plans(OBServiceLinePlanID int, SPLongRangeServiceLineID int)
	if (len(@planGUIDList) = 0) 
		begin
			-- if no plans provided, we will update job codes for all plans
			insert into #Plans(OBServiceLinePlanID, SPLongRangeServiceLineID)
			select ob.OBServiceLinePlanID,sp.SPLongRangeServiceLineID
			from [ob].[DimOBServiceLinePlan] ob
				inner join [fw].[DimDepartment] dpt
					on ob.EntityID=dpt.EntityID
				inner join [sp].[DimSPLongRangeServiceLine] sp
					on dpt.DepartmentID=sp.EntityID
			where 1=1
				and dpt.IsDepartmentRollup = 1
				and sp.ScenarioID = 0
				and sp.IsDeleted = 0
				and ob.IsDeleted = 0
		end
	else
		begin
			-- if plans are provided, we will only update job codes in specified plans
			insert into #Plans(OBServiceLinePlanID, SPLongRangeServiceLineID)
			select ob.OBServiceLinePlanID,sp.SPLongRangeServiceLineID
			from [ob].[DimOBServiceLinePlan] ob
				inner join dbo.ConvertCSGuidsToTable(@planGUIDList, ',') pg
					on pg.guid=ob.MemberGUID
				inner join [fw].[DimDepartment] dpt
					on ob.EntityID=dpt.EntityID
				inner join [sp].[DimSPLongRangeServiceLine] sp
					on dpt.DepartmentID=sp.EntityID
			where 1=1
				and dpt.IsDepartmentRollup = 1
				and sp.ScenarioID = 0
				and sp.IsDeleted = 0
				and ob.IsDeleted = 0
		end

--------------------------------------------------------------------------------------------------
-- Suppress percentage adjustments
--------------------------------------------------------------------------------------------------
set @sql = @sql
+'
update vr
set vr.Amount = -1,
	vr.Amount_Formula=''x''
--select *
from [clientob].[FactServiceLineRollupVar] vr
	inner join #Plans pl on vr.OBServiceLinePlanID=pl.OBServiceLinePlanID
where 1=1
	and vr.TimeClassID        = 18   --baseline
	and vr.AssumptionID       = 18   --adjustment
	and vr.FiscalMonthID      = 0    --not specified
	and vr.UnitTypeID         = 142  --percentage
	and vr.DataTypeID         = 2    --var
	and vr.OBForecastDetailID = 36   --volume
	and vr.FiscalYearID       = '
+ cast(@budgetyear as nvarchar(4))
+ ' --current budget year
'

--------------------------------------------------------------------------------------------------
-- Delete existing service line volume adjustments
--------------------------------------------------------------------------------------------------
set @sql = @sql
+'
delete vr
--select *
from [clientob].[FactServiceLineVar] vr
	inner join #Plans pl on vr.OBServiceLinePlanID=pl.OBServiceLinePlanID
where 1=1
	and vr.TimeClassID        = 18   --baseline
	and vr.AssumptionID       = 18   --adjustment
	and vr.FiscalMonthID      = 0    --not specified
	and vr.UnitTypeID         = 140  --volume
	and vr.DataTypeID         = 2    --var
	and vr.OBForecastDetailID = 36   --volume
	and vr.FiscalYearID = '
+ cast(@budgetyear as nvarchar(4))
+ ' --current budget year
'

--------------------------------------------------------------------------------------------------
-- Insert service line volumes from SP to OB
--------------------------------------------------------------------------------------------------
set @sql = @sql
+'
insert into [clientob].[FactServiceLineVar]
(
	[AssumptionID], 
	[DataTypeID], 
	[FiscalMonthID], 
	[FiscalYearID], 
	[ModelingServiceLineID], 
	[OBForecastDetailID], 
	[OBServiceLinePlanID], 
	[TimeClassID], 
	[UnitTypeID], 
	[Amount], 
	[IsDeleted], 
	[HistoryItemGUID]
)
select
	AssumptionID          = 18,
	DataTypeID            = 2,
	FiscalMonthID         = 0,
	FiscalYearID          = '
+ cast(@budgetyear as nvarchar(4))
+ ',
	ModelingServiceLineID = fct.ModelingServiceLineID,
	OBForecastDetailID    = 36,
	OBServiceLinePlanID   = pg.OBServiceLinePlanID,
	TimeClassID           = 18,
	UnitTypeID            = 140,
	Amount                = sum(fct.Amount),
	IsDeleted             = 0,
	HistoryItemGUID       = '''
+ cast(@higuid as nvarchar(36))
+ '''
from [clientsp].[FactServiceLineRevenue] fct
	inner join #Plans pg
		on fct.SPLongRangeServiceLineID = pg.SPLongRangeServiceLineID
where 1=1
	and fct.TimeClassID     = 3    --forecast
	and fct.DataTypeID      = 3    --output
	and fct.UnitTypeID      = 140  --volume
	and fct.AccountRollupID = 3    --volumes
	and fct.FiscalYearID    = '
+ cast(@budgetyear as nvarchar(4))
+ ' --current budget year
group by
	fct.ModelingServiceLineID,
	pg.OBServiceLinePlanID
'

--------------------------------------------------------------------------------------------------
-- Run/Print SQL
--------------------------------------------------------------------------------------------------
if @IsDebugOnly=1
	begin
		print(@sql)
	end
else
	begin
		exec(@sql)
	end

--------------------------------------------------------------------------------------------------
-- Invalidate cache
--------------------------------------------------------------------------------------------------
if @IsDebugOnly=1
	begin
		print('Model workbook cache is not invalidated in debug mode.')
	end
else
	begin
		if (@planGUIDList = '') 
			begin
				exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '957dd809-6299-4ec2-81fc-5452df805e8e', 'procOBSPSLForecastYr1VoltoOBBaseline'
			end 
		else 
			begin
				declare @invalidateWhere nvarchar(max)
				set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @planGUIDList + ''','',''))'
				exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'procOBSPSLForecastYr1VoltoOBBaseline'
			end
	end	

--------------------------------------------------------------------------------------------------
-- Clean-up
--------------------------------------------------------------------------------------------------
	drop table #Plans

end
GO


---------------------------------------------

-- ob.procOBSnapshotInsert
CREATE proc [ob].[procOBSnapshotInsert]
	@SnapshotCategory nvarchar(200)='Auto',
    @SnapshotName nvarchar(200)=''
/************************************************************************************************************************
** Author: Joel Gerber
** Create Date: 2014-07
** Description: Saves all the operating budgeting data in snapshot tables with a snapshot ID
** Last Modified: 2017-12-05
** GM Release: 2014.4
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
**	1		2014-09-15	JG					Adding Provider, Reimbursement, Service Line, and Financial Planning data sources
**	2		2015-09-25	cbb		D-03363		Adding joins to dimensions to exclude orphaned data
**	3		2016-02-03	cbb		D-03664		Adding missing fact table and dimension deletes
**  4		2017-05-02	cbb		B-15664		Refactoring and adding Budget Close category
**  5		2017-05-11	cbb		D-05935		fix join on wrong dimension
**  6		2017-06-06	cbb		B-15886		add var table snapshots
**  7		2017-11-09	apukii	B-17941		add ability to set snapshots name
**  8		2017-11-14	apukii	B-17941		modified category limits
**  9		2017-11-20	apukii	B-17941		delete snapshots only in case Budget Close
**  10		2017-11-24	apukii	B-17941		replaced [fw].[DimForecastDetail] with [ob].[DimOBForecastDetail] for FactProviderVarSnapshot and FactCDMVarSnapshot
**  11      2017-12-05  apukii  B-18163     allowed all new snapshots to include var table data
*************************************************************************************************************************/
as
begin

----------------------------------------------------------------------------------------------------
-- Populate temp table with snapshots to be deleted
----------------------------------------------------------------------------------------------------
	; -- CTE - previous statement must be terminated with a semicolon
	with oldsnapshots
	as
	(
		select
			Category,
			OBSnapshotID,
			Num = row_number() over (PARTITION BY Category order by Date desc, OBSnapshotID desc)
		from [ob].[DimOBSnapshot]
	)
	select OBSnapshotID, Num
	into #tempOldSnapshotIDs
	from oldsnapshots
	where 1=1
		and Category = 'Budget Close' and Num > 1

----------------------------------------------------------------------------------------------------
-- Delete old snapshots
----------------------------------------------------------------------------------------------------
	if (select count(OBSnapshotID) from #tempOldSnapshotIDs) > 0 and @SnapshotCategory = 'Budget Close'
		begin
			delete fct from [ob].[FactAccountSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactStaffingPCSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactReportingMonthlySnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactGlobalStatisticsSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactServiceLineSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactCDMSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactReimbursementPayorSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactReimbursementAccountSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactProviderSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
-- CID 6 BEGIN
			delete fct from [ob].[FactAccountSubtableVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactAccountVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactCDMVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactProviderVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
			delete fct from [ob].[FactStaffingPCVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
-- CID 6 END			
			--dimension
			delete fct from [ob].[DimOBSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID
		end

----------------------------------------------------------------------------------------------------
-- Create new snapshot record
----------------------------------------------------------------------------------------------------
	declare @fiscalYear nvarchar(200) = (select top 1 convert(int, Setting) + 1 from [dbo].[DBSetting] where [Name] = 'OB_Current_Year')
    declare @newSnapDate nvarchar(200) = left(convert(nvarchar,getdate(),120), 16)
	declare @newSnapName nvarchar(200)
	
    select @newSnapName =
        case @SnapshotName
            when '' then @newSnapDate
            else @SnapshotName
        end

	select @newSnapName =
		case @SnapshotCategory
			when 'Budget Close' then 'Budget Close - FY' + @fiscalYear + ' - ' + @newSnapDate
			else @newSnapName
		end 

	insert into [ob].[DimOBSnapshot]
		(Name, Category, Date)
	values
		(@newSnapName, @SnapshotCategory, @newSnapDate)

	SELECT CAST(SCOPE_IDENTITY() as int);

	declare @newSnapID varchar(16)
	select @newSnapID = OBsnapshotID 
	from [ob].[DimOBSnapshot]
	where 1=1
		and Date = @newSnapDate
		and OBSnapshotID <> 0

----------------------------------------------------------------------------------------------------
-- FactAccountSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactAccountSnapshot]
	(
		DepartmentalBudgetID, 
		AccountID, 
		FiscalYearID, 
		TimeClassID, 
		UnitTypeID, 
		DataTypeID, 
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		MonthsLoaded,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.DepartmentalBudgetID, 
		fct.AccountID, 
		fct.FiscalYearID, 
		fct.TimeClassID, 
		fct.UnitTypeID,  
		fct.DataTypeID, 
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.MonthsLoaded,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactAccount] fct
		inner join [ob].[DimDepartmentalBudget] dmb
			on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID
		inner join [fw].[DimAccount] dma
			on fct.AccountID=dma.AccountID

----------------------------------------------------------------------------------------------------
-- FactStaffingPCSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactStaffingPCSnapshot]
	(
		DepartmentalBudgetID, 
		PayCodeGroupID, 
		JobCodeID, 
		FiscalYearID, 
		TimeClassID, 
		UnitTypeID, 
		DataTypeID,
		PayCodeID,
		EmployeeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		MonthsLoaded,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.DepartmentalBudgetID, 
		fct.PayCodeGroupID, 
		fct.JobCodeID, 
		fct.FiscalYearID, 
		fct.TimeClassID, 
		fct.UnitTypeID, 
		fct.DataTypeID,
		fct.PayCodeID,
		fct.EmployeeID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.MonthsLoaded,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from 
		[clientob].[FactStaffingPC] fct
			inner join [ob].[DimDepartmentalBudget] dmb
				on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID
			inner join [fw].[DimPayCodeGroup] dmg
				on fct.PayCodeGroupID=dmg.PayCodeGroupID
			inner join [fw].[DimPayCode] dmp
				on fct.PayCodeID=dmp.PayCodeID
			inner join [fw].[DimJobCode] dmj
				on fct.JobCodeID=dmj.JobCodeID
			inner join [fw].[DimEmployee] dme
				on fct.EmployeeID=dme.EmployeeID

----------------------------------------------------------------------------------------------------
-- FactReportingMonthlySnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactReportingMonthlySnapshot]
	(
		DepartmentalBudgetID, 
		FinancialReportingID, 
		FiscalYearID, 
		TimeClassID, 
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.DepartmentalBudgetID, 
		fct.FinancialReportingID, 
		fct.FiscalYearID, 
		fct.TimeClassID, 
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from 
		[clientob].[FactReportingMonthly] fct
			inner join [ob].[DimDepartmentalBudget] dmb
				on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID
			inner join [ob].[DimFinancialReporting] dmf		-- CID 5
				on fct.FinancialReportingID=dmf.FinancialReportingID

----------------------------------------------------------------------------------------------------
-- FactGlobalStatisticsSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactGlobalStatisticsSnapshot]
	(
		OBGlobalStatisticsPlanID, 
		OBGlobalStatisticID, 
		FiscalYearID, 
		TimeClassID, 
		UnitTypeID, 
		DataTypeID, 
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		MonthsLoaded,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.OBGlobalStatisticsPlanID, 
		fct.OBGlobalStatisticID, 
		fct.FiscalYearID, 
		fct.TimeClassID, 
		fct.UnitTypeID, 
		fct.DataTypeID, 
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.MonthsLoaded,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactGlobalStatistics] fct
		inner join [ob].[DimOBGlobalStatisticsPlan] dmp
			on fct.OBGlobalStatisticsPlanID=dmp.OBGlobalStatisticsPlanID
		inner join [ob].[DimOBGlobalStatistics] dmg
			on fct.OBGlobalStatisticID=dmg.OBGlobalStatisticID

----------------------------------------------------------------------------------------------------
-- FactServiceLineSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactServiceLineSnapshot]
	(
		OBServiceLinePlanID,
		ModelingServiceLineID, 
		OBForecastDetailID,
		DataTypeID,
		UnitTypeID, 
		FiscalYearID, 
		TimeClassID, 
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.OBServiceLinePlanID,
		fct.ModelingServiceLineID, 
		fct.OBForecastDetailID,
		fct.DataTypeID,
		fct.UnitTypeID, 
		fct.FiscalYearID, 
		fct.TimeClassID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactServiceLine] fct
		inner join [ob].[DimOBServiceLinePlan] dmp
			on fct.OBServiceLinePlanID=dmp.OBServiceLinePlanID
		inner join [fw].[DimModelingServiceLine] dmm
			on fct.ModelingServiceLineID=dmm.ModelingServiceLineID
		inner join [ob].[DimOBForecastDetail] dmf
			on fct.OBForecastDetailID=dmf.OBForecastDetailID
				
----------------------------------------------------------------------------------------------------
-- FactCDMSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactCDMSnapshot]
	(
		ChargeCodeID,
		DataTypeID, 
		FiscalYearID,
		DepartmentalBudgetID,
		OBForecastDetailID, 
		PatientClassID, 
		TimeClassID, 
		UnitTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.ChargeCodeID,
		fct.DataTypeID, 
		fct.FiscalYearID,
		fct.DepartmentalBudgetID,
		fct.OBForecastDetailID, 
		fct.PatientClassID, 
		fct.TimeClassID, 
		fct.UnitTypeID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactCDM] fct
		inner join [fw].[DimChargeCode] dmc
			on fct.ChargeCodeID=dmc.ChargeCodeID
		inner join [ob].[DimDepartmentalBudget] dmd
			on fct.DepartmentalBudgetID=dmd.DepartmentalBudgetID
		inner join [ob].[DimOBForecastDetail] dmf
			on fct.OBForecastDetailID=dmf.OBForecastDetailID

		
----------------------------------------------------------------------------------------------------
-- FactReimbursementPayorSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactReimbursementPayorSnapshot]
	(
		DataTypeID,
		FiscalYearID,
		OBForecastDetailID, 
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		PayorID,
		PayorGroupID,
		TimeClassID, 
		UnitTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		MonthsLoaded,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.DataTypeID,
		fct.FiscalYearID,
		fct.OBForecastDetailID, 
		fct.OBReimbursementPlanID,
		fct.PatientReimbursementGroupID,
		fct.PayorID,
		fct.PayorGroupID,
		fct.TimeClassID, 
		fct.UnitTypeID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.MonthsLoaded,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactReimbursement] fct
		inner join [ob].[DimOBForecastDetail] dmf
			on fct.OBForecastDetailID=dmf.OBForecastDetailID
		inner join [ob].[DimOBReimbursementPlan] dmr
			on fct.OBReimbursementPlanID=dmr.OBReimbursementPlanID
		inner join [fw].[DimPatientReimbursementGroup] dmp
			on fct.PatientReimbursementGroupID=dmp.PatientReimbursementGroupID
		inner join [fw].[DimPayor] dmy
			on fct.PayorID=dmy.PayorID
		inner join [fw].[DimPayorGroup] dmg
			on fct.PayorGroupID=dmg.PayorGroupID

----------------------------------------------------------------------------------------------------
-- FactReimbursementAccountSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactReimbursementAccountSnapshot]
	(
		AccountID,
		DataTypeID,
		FiscalYearID,
		OBReimbursementPlanID,
		PatientReimbursementGroupID,
		TimeClassID, 
		UnitTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		MonthsLoaded,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.AccountID,
		fct.DataTypeID,
		fct.FiscalYearID,
		fct.OBReimbursementPlanID,
		fct.PatientReimbursementGroupID,
		fct.TimeClassID, 
		fct.UnitTypeID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.MonthsLoaded,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactReimbursementAccount] fct
		inner join [fw].[DimAccount] dma
			on fct.AccountID=dma.AccountID
		inner join [ob].[DimOBReimbursementPlan] dmr
			on fct.OBReimbursementPlanID=dmr.OBReimbursementPlanID
		inner join [fw].[DimPatientReimbursementGroup] dmp
			on fct.PatientReimbursementGroupID=dmp.PatientReimbursementGroupID

----------------------------------------------------------------------------------------------------
-- FactProviderSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactProviderSnapshot]
	(
		DataTypeID,
		FiscalYearID,
		DepartmentalBudgetID,
		TimeClassID, 
		UnitTypeID,
		ProviderID,
		OBForecastDetailID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		Yearly,
		Total,
		YTD,
		MonthsLoaded,
		IsDeleted,
		HistoryItemGUID,
		OBSnapshotID
	)
	select --select top 100
		fct.DataTypeID,
		fct.FiscalYearID,
		fct.DepartmentalBudgetID,
		fct.TimeClassID, 
		fct.UnitTypeID,
		fct.ProviderID,
		fct.OBForecastDetailID,
		fct.Month01,
		fct.Month02,
		fct.Month03,
		fct.Month04,
		fct.Month05,
		fct.Month06,
		fct.Month07,
		fct.Month08,
		fct.Month09,
		fct.Month10,
		fct.Month11,
		fct.Month12,
		fct.Yearly,
		fct.Total,
		fct.YTD,
		fct.MonthsLoaded,
		fct.IsDeleted,
		fct.HistoryItemGUID,
		@newSnapID as SnapshotID
	from [clientob].[FactProvider] fct		
		inner join [ob].[DimDepartmentalBudget] dmd
			on fct.DepartmentalBudgetID=dmd.DepartmentalBudgetID
		inner join [fw].[DimProvider] dmp
			on fct.ProviderID=dmp.ProviderID
		inner join [ob].[DimOBForecastDetail] dmf
			on fct.OBForecastDetailID=dmf.OBForecastDetailID

----------------------------------------------------------------------------------------------------
-- FactAccountSubtableVarSnapshot
----------------------------------------------------------------------------------------------------
	insert into [ob].[FactAccountSubtableVarSnapshot]
	(
		[AccountID],
		[AdjustmentCategoryID],
		[AssumptionID],
		[FiscalYearID],
		[DepartmentalBudgetID],
		[TimeClassID],
		[UnitTypeID],
		[Comment],
		[Comment_Comment],
		[Comment_Formula],
		[Month01],
		[Month02],
		[Month03],
		[Month04],
		[Month05],
		[Month06],
		[Month07],
		[Month08],
		[Month09],
		[Month10],
		[Month11],
		[Month12],
		[Yearly],
		[IsDeleted],
		[HistoryItemGUID],
		[OBSnapshotID]
	)
	SELECT
		fct.[AccountID],
		fct.[AdjustmentCategoryID],
		fct.[AssumptionID],
		fct.[FiscalYearID],
		fct.[DepartmentalBudgetID],
		fct.[TimeClassID],
		fct.[UnitTypeID],
		fct.[Comment],
		fct.[Comment_Comment],
		fct.[Comment_Formula],
		fct.[Month01],
		fct.[Month02],
		fct.[Month03],
		fct.[Month04],
		fct.[Month05],
		fct.[Month06],
		fct.[Month07],
		fct.[Month08],
		fct.[Month09],
		fct.[Month10],
		fct.[Month11],
		fct.[Month12],
		fct.[Yearly],
		fct.[IsDeleted],
		fct.[HistoryItemGUID],
		@newSnapID as OBSnapshotID
	FROM [clientob].[FactAccountSubtableVar] fct
		join [fw].[DimAccount] da
			on fct.AccountID = da.AccountID
		join [ob].[DimAdjustmentCategory] dac
			on fct.AdjustmentCategoryID = dac.AdjustmentCategoryID
		join [fw].[DimAssumption] das
			on fct.AssumptionID = das.AssumptionID
		join [ob].[DimDepartmentalBudget] ddb
			on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID

----------------------------------------------------------------------------------------------------
-- FactAccountVarSnapshot
----------------------------------------------------------------------------------------------------
	INSERT INTO [ob].[FactAccountVarSnapshot]
	(
		[AccountID],
		[AssumptionID],
		[FiscalMonthID],
		[FiscalYearID],
		[DepartmentalBudgetID],
		[RowNumberID], 
		[TimeClassID],
		[UnitTypeID],
		[Amount], 
		[Amount_Comment],
		[Amount_Formula],
		[Comment],
		[Comment_Comment],
		[Comment_Formula],
		[TextValue],
		[TextValue_Comment],
		[TextValue_Formula],
		[IsDeleted],
		[HistoryItemGUID],
		[OBSnapshotID]
	)
	select
		fct.[AccountID],
		fct.[AssumptionID],
		fct.[FiscalMonthID],
		fct.[FiscalYearID],
		fct.[DepartmentalBudgetID],
		fct.[RowNumberID], 
		fct.[TimeClassID],
		fct.[UnitTypeID],
		fct.[Amount], 
		fct.[Amount_Comment],
		fct.[Amount_Formula],
		fct.[Comment],
		fct.[Comment_Comment],
		fct.[Comment_Formula],
		fct.[TextValue],
		fct.[TextValue_Comment],
		fct.[TextValue_Formula],
		fct.[IsDeleted],
		fct.[HistoryItemGUID],
		@newSnapID as [OBSnapshotID]
	from [clientob].[FactAccountVar] fct
		join [fw].[DimAccount] da
			on fct.AccountID = da.AccountID
		join [fw].[DimAssumption] das
			on fct.AssumptionID = das.AssumptionID
		join [ob].[DimDepartmentalBudget] ddb
			on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID

----------------------------------------------------------------------------------------------------
-- FactCDMVarSnapshot
----------------------------------------------------------------------------------------------------
	INSERT INTO [ob].[FactCDMVarSnapshot]
	(
		[AssumptionID],
		[ChargeCodeID],
		[DataTypeID],
		[FiscalMonthID],
		[FiscalYearID],
		[DepartmentalBudgetID],
		[OBForecastDetailID],
		[PatientClassID],
		[TimeClassID],
		[UnitTypeID],
		[Amount],
		[Amount_Comment],
		[Amount_Formula],
		[Comment],
		[TextValue],
		[TextValue_Comment],
		[TextValue_Formula],
		[IsDeleted],
		[HistoryItemGUID],
		[OBSnapshotID]
	)
	select
		fct.[AssumptionID],
		fct.[ChargeCodeID],
		fct.[DataTypeID],
		fct.[FiscalMonthID],
		fct.[FiscalYearID],
		fct.[DepartmentalBudgetID],
		fct.[OBForecastDetailID],
		fct.[PatientClassID],
		fct.[TimeClassID],
		fct.[UnitTypeID],
		fct.[Amount],
		fct.[Amount_Comment],
		fct.[Amount_Formula],
		fct.[Comment],
		fct.[TextValue],
		fct.[TextValue_Comment],
		fct.[TextValue_Formula],
		fct.[IsDeleted],
		fct.[HistoryItemGUID],
		@newSnapID as [OBSnapshotID]
	from [clientob].[FactCDMVar] fct
		join [fw].[DimChargeCode] dcc
			on fct.ChargeCodeID = dcc.ChargeCodeID
		join [ob].[DimOBForecastDetail] dfd
			on fct.OBForecastDetailID = dfd.OBForecastDetailID
		join [fw].[DimAssumption] das
			on fct.AssumptionID = das.AssumptionID
		join [ob].[DimDepartmentalBudget] ddb
			on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID
		join [fw].[DimPatientClass] dpc
			on fct.PatientClassID = dpc.PatientClassID

----------------------------------------------------------------------------------------------------
-- FactProviderVarSnapshot
----------------------------------------------------------------------------------------------------
	INSERT INTO [ob].[FactProviderVarSnapshot]
	(
		[AssumptionID],
		[FiscalMonthID],
		[FiscalYearID],
		[DepartmentalBudgetID],
		[OBForecastDetailID],
		[ProviderID],
		[TimeClassID],
		[UnitTypeID],
		[Amount],
		[Amount_Comment],
		[Amount_Formula],
		[TextValue],
		[TextValue_Comment],
		[TextValue_Formula],
		[IsDeleted],
		[HistoryItemGUID],
		[OBSnapshotID]
	)
	select
		fct.[AssumptionID],
		fct.[FiscalMonthID],
		fct.[FiscalYearID],
		fct.[DepartmentalBudgetID],
		fct.[OBForecastDetailID],
		fct.[ProviderID],
		fct.[TimeClassID],
		fct.[UnitTypeID],
		fct.[Amount],
		fct.[Amount_Comment],
		fct.[Amount_Formula],
		fct.[TextValue],
		fct.[TextValue_Comment],
		fct.[TextValue_Formula],
		fct.[IsDeleted],
		fct.[HistoryItemGUID],
		@newSnapID as [OBSnapshotID]
	from [clientob].[FactProviderVar] fct
		join [fw].[DimProvider] dp
			on fct.ProviderID = dp.ProviderID
		join [ob].[DimOBForecastDetail] dfd
			on fct.OBForecastDetailID = dfd.OBForecastDetailID
		join [fw].[DimAssumption] das
			on fct.AssumptionID = das.AssumptionID
		join [ob].[DimDepartmentalBudget] ddb
			on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID

----------------------------------------------------------------------------------------------------
-- FactStaffingPCVarSnapshot
----------------------------------------------------------------------------------------------------
	INSERT INTO [ob].[FactStaffingPCVarSnapshot]
	(
		[AssumptionID],
		[EmployeeID],
		[FiscalMonthID],
		[FiscalYearID],
		[JobCodeID],
		[DepartmentalBudgetID],
		[PayCodeGroupID],
		[TimeClassID],
		[UnitTypeID],
		[Amount],
		[Amount_Comment],
		[Amount_Formula],
		[Comment],
		[Comment_Comment],
		[Comment_Formula],
		[TextValue],
		[TextValue_Comment],
		[TextValue_Formula],
		[IsDeleted],
		[HistoryItemGUID],
		[OBSnapshotID]
	)
	select
		fct.[AssumptionID],
		fct.[EmployeeID],
		fct.[FiscalMonthID],
		fct.[FiscalYearID],
		fct.[JobCodeID],
		fct.[DepartmentalBudgetID],
		fct.[PayCodeGroupID],
		fct.[TimeClassID],
		fct.[UnitTypeID],
		fct.[Amount],
		fct.[Amount_Comment],
		fct.[Amount_Formula],
		fct.[Comment],
		fct.[Comment_Comment],
		fct.[Comment_Formula],
		fct.[TextValue],
		fct.[TextValue_Comment],
		fct.[TextValue_Formula],
		fct.[IsDeleted],
		fct.[HistoryItemGUID],
		@newSnapID as [OBSnapshotID]
	from [clientob].[FactStaffingPCVar] fct
		join [fw].[DimEmployee] de
			on fct.EmployeeID = de.EmployeeID
		join [fw].[DimJobCode] djc
			on fct.JobCodeID = djc.JobCodeID
		join [fw].[DimPayCodeGroup] dpc
			on fct.PayCodeGroupID = dpc.PayCodeGroupID
		join [fw].[DimAssumption] das
			on fct.AssumptionID = das.AssumptionID
		join [ob].[DimDepartmentalBudget] ddb
			on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID

----------------------------------------------------------------------------------------------------
-- End procedure
----------------------------------------------------------------------------------------------------
end

RETURN
GO


---------------------------------------------

-- ob.procOptimizationRebuildIndexesData
CREATE PROC [ob].[procOptimizationRebuildIndexesData]
	@forceExecution BIT = 0
AS

/************************************************************
** Author: akowalski
** Create Date: 2013-02-18
** Description: Finds all data tables in the OB schemas and rebuilds indexes, for use after large inserts/deletes
** Last Modified: 2017-01-12
** GM Release: 2013-03-12
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-02-19	DK		56588	Adding update statistics command
** 1		2016-09-09	GF		12897	Include fillin tables
** 2		2017-01-12	VY		05020	Add @forceExecution optional parameter
** 3		2017-01-17	cbb		05447	add missing "("
*************************************************************/

SET NOCOUNT ON;

	IF @forceExecution = 1
	BEGIN
		DECLARE @SCHEMA nvarchar(256)
		DECLARE @FactTableName nvarchar(256)
		DECLARE @SQL nvarchar(1024)
		DECLARE FactTableCursor CURSOR FOR 
		select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where 
		(
			t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map')
			or
			t.schema_id in(select schema_id from sys.schemas where name in('dbo', 'data')) and (t.name like 'scorefillin%')
		)
		and t.object_ID not in (
			select distinct t.object_id from sys.tables t
			inner join sys.indexes i on t.object_id=i.object_id
			inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
			where p.data_compression<>0
			) order by t.name
		open FactTableCursor

		FETCH NEXT FROM FactTableCursor 
		INTO @FactTableName, @SCHEMA
		WHILE @@FETCH_STATUS = 0
		BEGIN

			--=================== BEGIN CID 1 =====================
			set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80)
			update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
			--=================== END CID 1 =======================
			--print @SQL
			EXECUTE sp_executesql @SQL 
			FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
		END

		CLOSE FactTableCursor
		DEALLOCATE FactTableCursor

		DECLARE FactTableCursor CURSOR FOR 
		select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map')
		and t.object_ID not in (
			select distinct t.object_id from sys.tables t
			inner join sys.indexes i on t.object_id=i.object_id
			inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
			where p.data_compression=0
			) order by t.name
		open FactTableCursor

		FETCH NEXT FROM FactTableCursor 
		INTO @FactTableName, @SCHEMA
		WHILE @@FETCH_STATUS = 0
		BEGIN

			--=================== BEGIN CID 1 =====================
			--begin cid 3
			set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80,DATA_COMPRESSION = PAGE)
			update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
			--end cid 3
			--=================== END CID 1 =======================
			--print @SQL
			EXECUTE sp_executesql @SQL 
			FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
		END

		CLOSE FactTableCursor
		DEALLOCATE FactTableCursor
	END
	ELSE
	BEGIN
		--Request 'OB Rebuild Indexes' task to rebuild indexes on the next run
		UPDATE [ob].[SystemSetting] SET [Value] = '1' WHERE [Name] = 'OB_Rebuild_Indexes'
	END
GO


---------------------------------------------

-- ob.procOptimizationRebuildIndexesDimensions
CREATE proc [ob].[procOptimizationRebuildIndexesDimensions] as

/************************************************************
** Author: akowalski
** Create Date: 2013-02-18
** Description: Finds all dimension tables in the OB schemas and rebuilds indexes, for after dimension customization.
** Last Modified: 2013-02-18
** GM Release: 2013-03-12
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-02-19	DK		56588	Adding update statistics command
**
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'dim%'
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'dim%'
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80,DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor


RETURN
GO


---------------------------------------------

-- ob.procOptimizationRebuildIndexesMapping
CREATE proc [ob].[procOptimizationRebuildIndexesMapping] as

/************************************************************
** Author: akowalski
** Create Date: 2013-02-18
** Description: Finds all mapping tables in the OB schemas and rebuilds indexes, for use after publishing.
** Last Modified: 2013-05-03
** GM Release: 2013-05-14
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2013-02-19	DK		56588	Adding update statistics command
** 2		2013-05-01	AKK		57940	Adding meexcelcell, emfmodeltemplate, scoremeasure, and emfmodeltemplateworksheet
** 3		2013-05-03	AKK		57940	Adding MEScorePlaceholderLabel
** 4		2016-09-09	GJF		12897	Change fill factor to 100	
*************************************************************/


SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'fact%map'
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression<>0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=100)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'fact%map'
	and t.object_ID not in (
		select distinct t.object_id from sys.tables t
		inner join sys.indexes i on t.object_id=i.object_id
		inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id
		where p.data_compression=0
		) order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		--=================== BEGIN CID 1 =====================
		set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=100,DATA_COMPRESSION = PAGE)
		update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN'
		--=================== END CID 1 =======================
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	--=================== BEGIN CID 2 =====================
	alter index all on dbo.meexcelcell REBUILD WITH (FILLFACTOR=100)
	update statistics dbo.meexcelcell WITH FULLSCAN
	
	alter index all on dbo.emfmodeltemplate REBUILD WITH (FILLFACTOR=100)
	update statistics dbo.emfmodeltemplate WITH FULLSCAN
	
	alter index all on dbo.scoremeasure REBUILD WITH (FILLFACTOR=100)
	update statistics dbo.scoremeasure WITH FULLSCAN
	
	alter index all on dbo.emfmodeltemplateworksheet REBUILD WITH (FILLFACTOR=100)
	update statistics dbo.emfmodeltemplateworksheet WITH FULLSCAN
	--=================== END CID 2 =======================
	--=================== BEGIN CID 3 =====================
	alter index all on dbo.mescoreplaceholderlabel REBUILD WITH (FILLFACTOR=100)
	update statistics dbo.mescoreplaceholderlabel WITH FULLSCAN
	--=================== END CID 3 =======================
GO


---------------------------------------------

-- ob.procRosterToDeptBudget
CREATE proc [ob].[procRosterToDeptBudget]
/****************************************************************************************************
** Author: cbb
** Create Date: 2016.11.15
** Description: Transfer roster budget to dept budget models
** Last Modified: 2018.01.17
** GM Release: 2017.1.1
****************************************************************************************************
** Change History
****************************************************************************************************
** CID	Date		Author	WI			Description
** 1	2017.02.06	cbb		d05501		filter out dollars for fixed staffing insert
** 2	2017.03.06	srk		D-05668 	Added issytemset = 0 to the insert fillin sections
** 3	2017.03.20	srk		TK-39537	Updated the invalidatecache section to use where by clause
** 4 	2017.03.20	srk		B-14939		Invalidate cache only for models where data does not tie out between roster tool and staffing tables
** 5 	2018.01.17	ljc		B-18199		Adding PayCodeGroupID in #JobCodeDept for var table merge
****************************************************************************************************/
as
	begin
--------------------------------------------------------------------------------------------------
-- Variables
--------------------------------------------------------------------------------------------------
	declare @higuid uniqueidentifier
	
	declare @currYear int
	select @currYear = Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year'
	
	declare @IsProjected bit
	select @IsProjected = IsProjectionHidden from [fp].[BudgetConfig] where IsActive = 1
	
	declare @assumptionID int
	select @assumptionID = dm.AssumptionID from [fw].[DimAssumption] dm where MemberGUID='8111719b-4232-49df-aced-1f5fe16df5b9'
	
	declare @planRefreshList as nvarchar(max) = ''
	
--------------------------------------------------------------------------------------------------
-- Logging
--------------------------------------------------------------------------------------------------
	exec procLogScript 'Update clientob.FactStaffingPCNonReporting from fp.viewRosterBudgetToStaffingPC' , @higuid output	
	print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36))

--------------------------------------------------------------------------------------------------
-- AGGREGATE ROSTER DATA FOR MERGE
--------------------------------------------------------------------------------------------------
--CID 2	
--	SELECT 
--		[DepartmentalBudgetID]
--		, [PayCodeGroupID]
--		, [PayCodeID]
--		, [JobCodeID]
--		, [EmployeeID]
--		, [FiscalYearID]
--		, [TimeClassID]
--		, [UnitTypeID]
--		, [DataTypeID]
--		, SUM([Month01]) AS	Month01
--		, SUM([Month02]) AS	Month02
--		, SUM([Month03]) AS	Month03
--		, SUM([Month04]) AS	Month04
--		, SUM([Month05]) AS	Month05
--		, SUM([Month06]) AS	Month06
--		, SUM([Month07]) AS	Month07
--		, SUM([Month08]) AS	Month08
--		, SUM([Month09]) AS	Month09
--		, SUM([Month10]) AS	Month10
--		, SUM([Month11]) AS	Month11
--		, SUM([Month12]) AS	Month12
--	INTO #RosterAggregate
--	FROM [fp].[viewRosterBudgetToStaffingPC] rb
--	GROUP BY
--		[DepartmentalBudgetID]
--		, [PayCodeGroupID]
--		, [PayCodeID]
--		, [JobCodeID]
--		, [EmployeeID]
--		, [FiscalYearID]
--		, [TimeClassID]
--		, [UnitTypeID]
--		, [DataTypeID]
--	HAVING NOT (
--		SUM([Month01]) = 0
--		AND SUM([Month02]) = 0
--		AND SUM([Month03]) = 0
--		AND SUM([Month04]) = 0
--		AND SUM([Month05]) = 0
--		AND SUM([Month06]) = 0
--		AND SUM([Month07]) = 0
--		AND SUM([Month08]) = 0
--		AND SUM([Month09]) = 0
--		AND SUM([Month10]) = 0
--		AND SUM([Month11]) = 0
--		AND SUM([Month12]) = 0
--		)

--CID 2

SELECT
		rb.[DepartmentalBudgetID]
		, rb.[PayCodeGroupID]
		, rb.[PayCodeID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
		, SUM(RB.[Month01]) as [Month01]
		, SUM(RB.[Month02]) as [Month02]
		, SUM(RB.[Month03]) as [Month03]
		, SUM(RB.[Month04]) as [Month04]
		, SUM(RB.[Month05]) as [Month05]
		, SUM(RB.[Month06]) as [Month06]
		, SUM(RB.[Month07]) as [Month07]
		, SUM(RB.[Month08]) as [Month08]
		, SUM(RB.[Month09]) as [Month09]
		, SUM(RB.[Month10]) as [Month10]
		, SUM(RB.[Month11]) as [Month11]
		, SUM(RB.[Month12]) as [Month12]
		, SUM(ROUND(RB.[Month01],4)) 
		+ SUM(ROUND(RB.[Month02],4)) 
		+ SUM(ROUND(RB.[Month03],4))
		+ SUM(ROUND(RB.[Month04],4)) 
		+ SUM(ROUND(RB.[Month05],4)) 
		+ SUM(ROUND(RB.[Month06],4))
		+ SUM(ROUND(RB.[Month07],4)) 
		+ SUM(ROUND(RB.[Month08],4)) 
		+ SUM(ROUND(RB.[Month09],4)) 
		+ SUM(ROUND(RB.[Month10],4)) 
		+ SUM(ROUND(RB.[Month11],4)) 
		+ SUM(ROUND(RB.[Month12],4)) as Total
	INTO #RosterAggregateInitial
	FROM [fp].[viewRosterBudgetToStaffingPC] RB
		WHERE 1=1 
	GROUP BY
		rb.[DepartmentalBudgetID]
		, rb.[PayCodeGroupID]
		, rb.[PayCodeID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]	
	
--ROSTER AGGREGATE TO INVALIDATE CACHE
		
	SELECT 
		rb.[DepartmentalBudgetID]
		, rb.[PayCodeGroupID]
		, rb.[PayCodeID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
		, SUM(RB.[Month01]) as [Month01]
		, SUM(RB.[Month02]) as [Month02]
		, SUM(RB.[Month03]) as [Month03]
		, SUM(RB.[Month04]) as [Month04]
		, SUM(RB.[Month05]) as [Month05]
		, SUM(RB.[Month06]) as [Month06]
		, SUM(RB.[Month07]) as [Month07]
		, SUM(RB.[Month08]) as [Month08]
		, SUM(RB.[Month09]) as [Month09]
		, SUM(RB.[Month10]) as [Month10]
		, SUM(RB.[Month11]) as [Month11]
		, SUM(RB.[Month12]) as [Month12]
	INTO #RosterAggregate
	FROM #RosterAggregateInitial RB
	LEFT JOIN [clientob].[FactStaffingPC] FS 
		on RB.DepartmentalBudgetID = FS.DepartmentalBudgetID
		and RB.JobCodeID = FS.JobCodeID
		and RB.PayCodeGroupID = FS.PayCodeGroupID
		and RB.UnitTypeID = FS.UnitTypeID
		and RB.TimeClassID = FS.TimeClassID
		and RB.FiscalYearID = FS.FiscalYearID
		and RB.DataTypeID = FS.DataTypeID
	GROUP BY
		rb.[DepartmentalBudgetID]
		, rb.[PayCodeGroupID]
		, rb.[PayCodeID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
	HAVING 
		ISNULL(ROUND(sum(RB.Total),0),0) <> ISNULL(ROUND(sum(FS.Total),0),0)

--CID 2


--------------------------------------------------------------------------------------------------
-- DISTINCT JOB CODE AND DEPARTMENTS FOR VAR TABLE MERGE
--------------------------------------------------------------------------------------------------
	SELECT distinct
		[DepartmentalBudgetID],
		[PayCodeGroupID], --CID 5 Include PayCodeGroupID in JobCode & Departments for var table merge
		[PayCodeID],
		[JobCodeID],
		0 [EmployeeID],
		[FiscalYearID],
		[TimeClassID],
		160 as [UnitTypeID],
		[DataTypeID]
	INTO #JobCodeDept
	FROM [fp].[viewRosterBudgetToStaffingPC] rb

--------------------------------------------------------------------------------------------------
-- AGGREGATE ROSTER DATA FOR MERGE WITH NO PAY CODE GROUP
--------------------------------------------------------------------------------------------------
--CID 2

SELECT
		rb.[DepartmentalBudgetID]
		, 0 as [PayCodeGroupID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
		, SUM(RB.[Month01]) as [Month01]
		, SUM(RB.[Month02]) as [Month02]
		, SUM(RB.[Month03]) as [Month03]
		, SUM(RB.[Month04]) as [Month04]
		, SUM(RB.[Month05]) as [Month05]
		, SUM(RB.[Month06]) as [Month06]
		, SUM(RB.[Month07]) as [Month07]
		, SUM(RB.[Month08]) as [Month08]
		, SUM(RB.[Month09]) as [Month09]
		, SUM(RB.[Month10]) as [Month10]
		, SUM(RB.[Month11]) as [Month11]
		, SUM(RB.[Month12]) as [Month12]
		, SUM(ROUND(RB.[Month01],4)) 
		+ SUM(ROUND(RB.[Month02],4)) 
		+ SUM(ROUND(RB.[Month03],4))
		+ SUM(ROUND(RB.[Month04],4)) 
		+ SUM(ROUND(RB.[Month05],4)) 
		+ SUM(ROUND(RB.[Month06],4))
		+ SUM(ROUND(RB.[Month07],4)) 
		+ SUM(ROUND(RB.[Month08],4)) 
		+ SUM(ROUND(RB.[Month09],4)) 
		+ SUM(ROUND(RB.[Month10],4)) 
		+ SUM(ROUND(RB.[Month11],4)) 
		+ SUM(ROUND(RB.[Month12],4)) as Total
	INTO #RosterAggregateNoPCGInitial
	FROM [fp].[viewRosterBudgetToStaffingPC] RB
		inner join [fw].[DimPayCodeGroup] pcg
			on rb.PayCodeGroupID = pcg.PayCodeGroupID
	where pcg.ProductiveClassID in (2,3)
-- CID 1 begin
		and UnitTypeID <> 34
	GROUP BY
		rb.[DepartmentalBudgetID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]	

-- Roster Aggregate No Pay Code Group TO INVALIDATE CACHE
		
	SELECT 
		rb.[DepartmentalBudgetID]
		, 0 as [PayCodeGroupID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
		, SUM(RB.[Month01]) as [Month01]
		, SUM(RB.[Month02]) as [Month02]
		, SUM(RB.[Month03]) as [Month03]
		, SUM(RB.[Month04]) as [Month04]
		, SUM(RB.[Month05]) as [Month05]
		, SUM(RB.[Month06]) as [Month06]
		, SUM(RB.[Month07]) as [Month07]
		, SUM(RB.[Month08]) as [Month08]
		, SUM(RB.[Month09]) as [Month09]
		, SUM(RB.[Month10]) as [Month10]
		, SUM(RB.[Month11]) as [Month11]
		, SUM(RB.[Month12]) as [Month12]
	INTO #RosterAggregateNoPayCodeGroup
	FROM #RosterAggregateNoPCGInitial RB
	LEFT JOIN [clientob].[FactStaffingPC] FS 
		on RB.DepartmentalBudgetID = FS.DepartmentalBudgetID
		and RB.JobCodeID = FS.JobCodeID
		and RB.PayCodeGroupID = FS.PayCodeGroupID
		and RB.UnitTypeID = FS.UnitTypeID
		and RB.TimeClassID = FS.TimeClassID
		and RB.FiscalYearID = FS.FiscalYearID
		and RB.DataTypeID = FS.DataTypeID
	GROUP BY
		rb.[DepartmentalBudgetID]
		, rb.[JobCodeID]
		, rb.[EmployeeID]
		, rb.[FiscalYearID]
		, rb.[TimeClassID]
		, rb.[UnitTypeID]
		, rb.[DataTypeID]
	HAVING 
		ISNULL(ROUND(sum(RB.Total),0),0) <> ISNULL(ROUND(sum(FS.Total),0),0)
		
--	SELECT 
--		DepartmentalBudgetID = [DepartmentalBudgetID],
--		PayCodeGroupID = 0,
--		JobCodeID = [JobCodeID],
--		EmployeeID = [EmployeeID],
--		FiscalYearID = [FiscalYearID],
--		TimeClassID = [TimeClassID],
--		UnitTypeID = [UnitTypeID],
--		DataTypeID = [DataTypeID],
--		Month01	= SUM([Month01]),
--		Month02	= SUM([Month02]),
--		Month03	= SUM([Month03]),
--		Month04	= SUM([Month04]),
--		Month05 = SUM([Month05]),
--		Month06 = SUM([Month06]),
--		Month07 = SUM([Month07]),
--		Month08 = SUM([Month08]),
--		Month09 = SUM([Month09]),
--		Month10 = SUM([Month10]),
--		Month11 = SUM([Month11]),
--		Month12 = SUM([Month12])
--	INTO #RosterAggregateNoPayCodeGroup
--	FROM [fp].[viewRosterBudgetToStaffingPC] rb
--		inner join [fw].[DimPayCodeGroup] pcg
--			on rb.PayCodeGroupID = pcg.PayCodeGroupID
--	where pcg.ProductiveClassID in (2,3)
---- CID 1 begin
--		and UnitTypeID <> 34
---- CID 2 end
--	GROUP BY
--		[DepartmentalBudgetID]
--		, [JobCodeID]
--		, [EmployeeID]
--		, [FiscalYearID]
--		, [TimeClassID]
--		, [UnitTypeID]
--		, [DataTypeID]
--	HAVING NOT (
--		SUM([Month01]) = 0
--		AND SUM([Month02]) = 0
--		AND SUM([Month03]) = 0
--		AND SUM([Month04]) = 0
--		AND SUM([Month05]) = 0
--		AND SUM([Month06]) = 0
--		AND SUM([Month07]) = 0
--		AND SUM([Month08]) = 0
--		AND SUM([Month09]) = 0
--		AND SUM([Month10]) = 0
--		AND SUM([Month11]) = 0
--		AND SUM([Month12]) = 0
--		)
-- CID 2




--------------------------------------------------------------------------------------------------
-- Job code temp table
--------------------------------------------------------------------------------------------------
	select distinct
		DepartmentalBudgetID	= ra.DepartmentalBudgetID,
		ModelGUID				= db.MemberGUID,
		JobCodeID				= ra.JobCodeID,
		JobCodeGUID				= jc.MemberGUID
	into #JobCodes
	from #RosterAggregateInitial ra
		inner join [ob].[DimDepartmentalBudget] db
			on ra.DepartmentalBudgetID = db.DepartmentalBudgetID
		inner join [fw].[DimJobCode] jc
			on ra.JobCodeID = jc.JobCodeID

CREATE UNIQUE CLUSTERED INDEX BASE ON #JobCodes (ModelGUID, JobCodeID);

--------------------------------------------------------------------------------------------------
-- Department temp table
--------------------------------------------------------------------------------------------------
	select distinct
		jc.DepartmentalBudgetID,
		db.MemberGUID
	into #Departments
	from #JobCodes jc
		inner join [ob].[DimDepartmentalBudget] db on jc.DepartmentalBudgetID = db.DepartmentalBudgetID
			
CREATE UNIQUE CLUSTERED INDEX BASE ON #Departments (MemberGUID);

	select distinct
		jc.DepartmentalBudgetID,
		db.MemberGUID
	into #DepartmentsCache
	from #RosterAggregate jc
		inner join [ob].[DimDepartmentalBudget] db on jc.DepartmentalBudgetID = db.DepartmentalBudgetID
			
CREATE UNIQUE CLUSTERED INDEX BASE ON #DepartmentsCache (MemberGUID);
--------------------------------------------------------------------------------------------------
-- Insert enable fill-in
--------------------------------------------------------------------------------------------------
;
	WITH SF AS
		(
			SELECT 
				[FillinGUID],
				[ModelGUID],
				[PlaceholderSectionMemberGUID],
				[FillinMemberGUID],
				[FillinMemberName],
				[IsSystemSet]
			FROM [dbo].[ScoreFillin] 
			WHERE PlaceholderSectionMemberGUID = 'da5abe63-1339-467d-ad83-89824174bc31'
		)
		MERGE SF AS TARGET
		USING #Departments AS SOURCE
			ON (
					1=1
					AND TARGET.ModelGUID	= 	SOURCE.MemberGUID
				)
		WHEN NOT MATCHED BY TARGET 		
		    THEN 
				INSERT([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [FillinMemberGUID], [FillinMemberName], [IsSystemSet]) 
				VALUES(newid(), MemberGUID, 'da5abe63-1339-467d-ad83-89824174bc31', 'fefe375c-656a-4a68-9c60-c5ce63f9919b', 'Enable', 0)
		WHEN 
			NOT MATCHED BY SOURCE 
		    THEN DELETE 
		; -- end merge
	
--------------------------------------------------------------------------------------------------
-- Refresh fill-in cache table for Forecast Detail dimension
--------------------------------------------------------------------------------------------------
	exec [dbo].[procScoreFillinTableRefreshByDimension] 
		@dimensionGUID = '7997659c-8a30-4d1e-86d2-0afb41c9e2fc',
		@isDebug = 0,
		@whereClause = ''

--------------------------------------------------------------------------------------------------
-- Insert missing job code fill-ins
--------------------------------------------------------------------------------------------------
	INSERT INTO [dbo].[ScoreFillin]	
	(
		[FillinGUID],
		[ModelGUID],
		[PlaceholderSectionMemberGUID],
		[PlaceholderIndex],
		[FillinMemberGUID],
		[FillinMemberName],
		[HistoryItemGUID],
		[IsSystemSet]
	)
    SELECT
		[FillinGUID]					= newid(),
		[ModelGUID]						= db.MemberGUID,
		[PlaceholderSectionMemberGUID]	= smg.SectionMemberGUID,
		[PlaceholderIndex]				= coalesce(fmax.MAXPlaceholderIndex,0)+cast(ROW_NUMBER() over (partition by db.MemberGUID, smg.SectionMemberGUID order by jc.Name) as int),
		[FillinMemberGUID]				= jc.MemberGUID,
		[FillinMemberName]				= jc.Name,
		[HistoryItemGUID]				= @higuid,
		case when smg.sectionmemberguid = '871804c8-1114-4cfa-b10d-ac401e2c88cb' then 0 else 1 end as [IsSystemSet]
--	into #scorefillin_new
    from #JobCodes jc_temp
	    inner join [ob].[DimDepartmentalBudget] db on jc_temp.DepartmentalBudgetID = db.DepartmentalBudgetID
	    inner join [fw].[DimJobCode] jc on jc_temp.JobCodeID = jc.JobCodeID
		cross join (select CAST('871804c8-1114-4cfa-b10d-ac401e2c88cb' AS uniqueidentifier) AS SectionMemberGUID UNION ALL select CAST('e9ce521d-6953-4636-94cd-b36798515385' AS uniqueidentifier) AS SectionMemberGUID) smg
		left join [dbo].[ScoreFillin] sf1 on
			db.MemberGUID = sf1.ModelGUID
			and jc.MemberGUID = sf1.FillinMemberGUID
		inner join 
		(
			select 
				ModelGUID,
				PlaceholderSectionMemberGUID,
				max(PlaceholderIndex) as MAXPlaceholderIndex
			from [dbo].[ScoreFillin] sf
			where PlaceholderSectionMemberGUID in ('871804c8-1114-4cfa-b10d-ac401e2c88cb','e9ce521d-6953-4636-94cd-b36798515385')
			group by ModelGUID, PlaceholderSectionMemberGUID
		) fmax ON 
			fmax.ModelGUID=db.MemberGUID
			and smg.SectionMemberGUID=fmax.PlaceholderSectionMemberGUID
	where 1=1
		and sf1.FillinMemberName is null

--------------------------------------------------------------------------------------------------
-- Refresh fill-in cache table for Forecast Detail dimension
--------------------------------------------------------------------------------------------------
	exec [dbo].[procScoreFillinTableRefreshByDimension] @dimensionGUID = '99bd1b87-5803-4847-aa83-80c2613aa41b', @isDebug = 0, @whereClause = ''

--------------------------------------------------------------------------------------------------
-- Run expansion profile fit update after fill-ins are added
--------------------------------------------------------------------------------------------------
	exec [dbo].[procMEScoreExpansionProfileFitPlans]
		@templateGUID = 'c397fa93-f151-4751-ad36-7a34aa7ee3ef',
		@planGUIDList = NULL,
		@expansionPadding = 10

--------------------------------------------------------------------------------------------------
-- Update var table settings
--------------------------------------------------------------------------------------------------
;
	WITH fctv AS
		(
			select
				DepartmentalBudgetID,
				PayCodeGroupID,
				JobCodeID,
				EmployeeID,
				FiscalYearID,
				FiscalMonthID,
				TimeClassID,
				UnitTypeID,
				AssumptionID,
				Amount,
				Amount_Formula,
				HistoryItemGUID,
				TransactionID
			from [clientob].[FactStaffingPCVar]
			where 1=1
--CID 5		and PayCodeGroupID = 0
				and UnitTypeID = 160
				and AssumptionID = @assumptionID
				and FiscalYearID >= @currYear 
				and IsDeleted = 0
		) 
		MERGE fctv AS TARGET
		USING #JobCodeDept AS SOURCE
			ON (
					1=1
					AND TARGET.[DepartmentalBudgetID]	= 	SOURCE.[DepartmentalBudgetID]
					AND TARGET.[JobCodeID] 				= 	SOURCE.[JobCodeID]
					AND TARGET.[EmployeeID] 			= 	SOURCE.[EmployeeID]
					AND TARGET.[FiscalYearID] 			= 	SOURCE.[FiscalYearID]
					AND TARGET.[TimeClassID] 			= 	SOURCE.[TimeClassID]
					and target.PayCodeGroupID			= 	source.PayCodeGroupID
					and target.UnitTypeID				=	source.UnitTypeID
					and target.AssumptionID				=	@assumptionID
					and target.FiscalYearID				=	source.FiscalYearID
				)
		WHEN NOT MATCHED BY TARGET 		
		    THEN 
				INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, FiscalMonthID, TimeClassID, UnitTypeID, AssumptionID, Amount, Amount_Formula, HistoryItemGUID, TransactionID) 
				VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, 0, FiscalYearID, 0, TimeClassID, 160, @assumptionID, 1, 'x', @higuid, -100) --CID 5 adding PayCodeGroupID
		WHEN MATCHED 
			AND TARGET.Amount <> 1
		    THEN 
				UPDATE 
				SET TARGET.Amount = 1,
					TARGET.Amount_Formula = 'x',
					TARGET.HistoryItemGUID = @higuid,
					TARGET.TransactionID = -100
		WHEN NOT MATCHED BY SOURCE 
			AND TARGET.TransactionID = -100
		    THEN DELETE
		; -- end merge
	; -- end with


--------------------------------------------------------------------------------------------------
-- MERGE clientob.FactStaffingPCNonReporting - Fixed staffing
--------------------------------------------------------------------------------------------------
	with fct as 
		(
			select
				DepartmentalBudgetID,
				PayCodeGroupID,
				JobCodeID,
				EmployeeID,
				FiscalYearID,
				TimeClassID,
				UnitTypeID,
				DataTypeID,
				Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12,
				HistoryItemGUID,
				TransactionID
			from [clientob].[FactStaffingPCNonReporting] nonr
			where 1=1
--				and nonr.FiscalYearID >= @currYear
				and nonr.DataTypeID = 4
				and nonr.PayCodeGroupID = 0
		)
		MERGE fct AS TARGET
		USING #RosterAggregateNoPCGInitial AS SOURCE
			ON (
					1=1
					AND TARGET.[DepartmentalBudgetID]	= 	SOURCE.[DepartmentalBudgetID]
					AND TARGET.[PayCodeGroupID] 		= 	SOURCE.[PayCodeGroupID]
					AND TARGET.[JobCodeID] 				= 	SOURCE.[JobCodeID]
					AND TARGET.[EmployeeID] 			= 	SOURCE.[EmployeeID]
					AND TARGET.[FiscalYearID] 			= 	SOURCE.[FiscalYearID]
					AND TARGET.[TimeClassID] 			= 	SOURCE.[TimeClassID]
					AND TARGET.[UnitTypeID] 			= 	SOURCE.[UnitTypeID]
--					AND TARGET.[DataTypeID] 			= 	4
				)
		WHEN 
			NOT MATCHED BY TARGET 		
		    THEN 
				INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) 
				VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 4, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100)
		WHEN 
			MATCHED 
			AND 
			(
				TARGET.Month01<>SOURCE.Month01
				OR TARGET.Month02<>SOURCE.Month02
				OR TARGET.Month03<>SOURCE.Month03
				OR TARGET.Month04<>SOURCE.Month04
				OR TARGET.Month05<>SOURCE.Month05
				OR TARGET.Month06<>SOURCE.Month06
				OR TARGET.Month07<>SOURCE.Month07
				OR TARGET.Month08<>SOURCE.Month08
				OR TARGET.Month09<>SOURCE.Month09
				OR TARGET.Month10<>SOURCE.Month10
				OR TARGET.Month11<>SOURCE.Month11
				OR TARGET.Month12<>SOURCE.Month12
			)
		    THEN 
				UPDATE 
				SET TARGET.Month01=SOURCE.Month01,
					TARGET.Month02=SOURCE.Month02,
					TARGET.Month03=SOURCE.Month03,
					TARGET.Month04=SOURCE.Month04,
					TARGET.Month05=SOURCE.Month05,
					TARGET.Month06=SOURCE.Month06,
					TARGET.Month07=SOURCE.Month07,
					TARGET.Month08=SOURCE.Month08,
					TARGET.Month09=SOURCE.Month09,
					TARGET.Month10=SOURCE.Month10,
					TARGET.Month11=SOURCE.Month11,
					TARGET.Month12=SOURCE.Month12,
					TARGET.HistoryItemGUID = @higuid
		WHEN 
			NOT MATCHED BY SOURCE 
			AND TARGET.TransactionID=-100
		    THEN DELETE 
		; -- end merge
	; -- end with

--------------------------------------------------------------------------------------------------
-- MERGE clientob.FactStaffingPCNonReporting - Wages
--------------------------------------------------------------------------------------------------
	with fct as 
		(
			select
				DepartmentalBudgetID,
				PayCodeGroupID,
				JobCodeID,
				EmployeeID,
				FiscalYearID,
				TimeClassID,
				UnitTypeID,
				DataTypeID,
				Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12,
				HistoryItemGUID,
				TransactionID
			from [clientob].[FactStaffingPCNonReporting] nonr
			where 1=1
				and nonr.FiscalYearID >= @currYear
				and nonr.DataTypeID = 4
				and nonr.PayCodeGroupID <> 0
		)
		MERGE fct AS TARGET
		USING #RosterAggregateInitial AS SOURCE
			ON (
					1=1
					AND TARGET.[DepartmentalBudgetID]	= 	SOURCE.[DepartmentalBudgetID]
					AND TARGET.[PayCodeGroupID] 		= 	SOURCE.[PayCodeGroupID]
					AND TARGET.[JobCodeID] 				= 	SOURCE.[JobCodeID]
					AND TARGET.[EmployeeID] 			= 	SOURCE.[EmployeeID]
					AND TARGET.[FiscalYearID] 			= 	SOURCE.[FiscalYearID]
					AND TARGET.[TimeClassID] 			= 	SOURCE.[TimeClassID]
					AND TARGET.[UnitTypeID] 			= 	SOURCE.[UnitTypeID]
	--				AND TARGET.[DataTypeID] 			= 	4
				)
		WHEN 
			NOT MATCHED BY TARGET 		
		    THEN 
				INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) 
				VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 4, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100)
		WHEN 
			MATCHED 
			AND 
			(
				TARGET.Month01<>SOURCE.Month01
				OR TARGET.Month02<>SOURCE.Month02
				OR TARGET.Month03<>SOURCE.Month03
				OR TARGET.Month04<>SOURCE.Month04
				OR TARGET.Month05<>SOURCE.Month05
				OR TARGET.Month06<>SOURCE.Month06
				OR TARGET.Month07<>SOURCE.Month07
				OR TARGET.Month08<>SOURCE.Month08
				OR TARGET.Month09<>SOURCE.Month09
				OR TARGET.Month10<>SOURCE.Month10
				OR TARGET.Month11<>SOURCE.Month11
				OR TARGET.Month12<>SOURCE.Month12
			)
		    THEN 
				UPDATE 
				SET TARGET.Month01=SOURCE.Month01,
					TARGET.Month02=SOURCE.Month02,
					TARGET.Month03=SOURCE.Month03,
					TARGET.Month04=SOURCE.Month04,
					TARGET.Month05=SOURCE.Month05,
					TARGET.Month06=SOURCE.Month06,
					TARGET.Month07=SOURCE.Month07,
					TARGET.Month08=SOURCE.Month08,
					TARGET.Month09=SOURCE.Month09,
					TARGET.Month10=SOURCE.Month10,
					TARGET.Month11=SOURCE.Month11,
					TARGET.Month12=SOURCE.Month12,
					TARGET.HistoryItemGUID = @higuid
		WHEN 
			NOT MATCHED BY SOURCE 
			AND TARGET.TransactionID=-100
		    THEN DELETE 
		; -- end merge
	; -- end with

--------------------------------------------------------------------------------------------------
-- MERGE clientob.FactStaffingPC - Fixed staffing
--------------------------------------------------------------------------------------------------
	with fctw as
	(
		select DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID
		from [clientob].[FactStaffingPC] fpc
		where DataTypeID = 3
		and PayCodeGroupID = 0
	)
		MERGE fctw AS TARGET
		USING #RosterAggregateNoPCGInitial AS SOURCE
			ON (
					1=1
					AND TARGET.[DepartmentalBudgetID]	= 	SOURCE.[DepartmentalBudgetID]
					AND TARGET.[PayCodeGroupID] 		= 	SOURCE.[PayCodeGroupID]
					AND TARGET.[JobCodeID] 				= 	SOURCE.[JobCodeID]
					AND TARGET.[EmployeeID] 			= 	SOURCE.[EmployeeID]
					AND TARGET.[FiscalYearID] 			= 	SOURCE.[FiscalYearID]
					AND TARGET.[TimeClassID] 			= 	SOURCE.[TimeClassID]
					AND TARGET.[UnitTypeID] 			= 	SOURCE.[UnitTypeID]
	--				AND TARGET.[DataTypeID] 			= 	SOURCE.[DataTypeID]
				)
		WHEN 
			NOT MATCHED BY TARGET
		    THEN 
				INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) 
				VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 3, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100)
		WHEN 
			MATCHED 
			AND 
			(
				TARGET.Month01<>SOURCE.Month01
				OR TARGET.Month02<>SOURCE.Month02
				OR TARGET.Month03<>SOURCE.Month03
				OR TARGET.Month04<>SOURCE.Month04
				OR TARGET.Month05<>SOURCE.Month05
				OR TARGET.Month06<>SOURCE.Month06
				OR TARGET.Month07<>SOURCE.Month07
				OR TARGET.Month08<>SOURCE.Month08
				OR TARGET.Month09<>SOURCE.Month09
				OR TARGET.Month10<>SOURCE.Month10
				OR TARGET.Month11<>SOURCE.Month11
				OR TARGET.Month12<>SOURCE.Month12
			)
		    THEN 
				UPDATE 
				SET TARGET.Month01=SOURCE.Month01,
					TARGET.Month02=SOURCE.Month02,
					TARGET.Month03=SOURCE.Month03,
					TARGET.Month04=SOURCE.Month04,
					TARGET.Month05=SOURCE.Month05,
					TARGET.Month06=SOURCE.Month06,
					TARGET.Month07=SOURCE.Month07,
					TARGET.Month08=SOURCE.Month08,
					TARGET.Month09=SOURCE.Month09,
					TARGET.Month10=SOURCE.Month10,
					TARGET.Month11=SOURCE.Month11,
					TARGET.Month12=SOURCE.Month12,
					TARGET.HistoryItemGUID = @higuid,
					TARGET.TransactionID = -100
			WHEN 
				NOT MATCHED BY SOURCE 
				AND TARGET.TransactionID = -100
		    THEN DELETE
		; -- end merge
	; -- end with

--------------------------------------------------------------------------------------------------
-- MERGE clientob.FactStaffingPC - Wages
--------------------------------------------------------------------------------------------------
	with fctw as
	(
		select 
			DepartmentalBudgetID, 
			PayCodeGroupID, 
			JobCodeID, 
			EmployeeID, 
			FiscalYearID, 
			TimeClassID, 
			UnitTypeID, 
			DataTypeID, 
			Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, 
			HistoryItemGUID, 
			TransactionID
		from [clientob].[FactStaffingPC] fpc
		where DataTypeID = 3
			and fpc.PayCodeGroupID<>0
	)
		MERGE fctw AS TARGET
		USING #RosterAggregateInitial AS SOURCE
			ON (
					1=1
					AND TARGET.[DepartmentalBudgetID]	= 	SOURCE.[DepartmentalBudgetID]
					AND TARGET.[PayCodeGroupID] 		= 	SOURCE.[PayCodeGroupID]
					AND TARGET.[JobCodeID] 				= 	SOURCE.[JobCodeID]
					AND TARGET.[EmployeeID] 			= 	SOURCE.[EmployeeID]
					AND TARGET.[FiscalYearID] 			= 	SOURCE.[FiscalYearID]
					AND TARGET.[TimeClassID] 			= 	SOURCE.[TimeClassID]
					AND TARGET.[UnitTypeID] 			= 	SOURCE.[UnitTypeID]
	--				AND TARGET.[DataTypeID] 			= 	SOURCE.[DataTypeID]
				)
		WHEN 
			NOT MATCHED BY TARGET
		    THEN 
				INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) 
				VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 3, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100)
		WHEN 
			MATCHED 
			AND 
			(
				TARGET.Month01<>SOURCE.Month01
				OR TARGET.Month02<>SOURCE.Month02
				OR TARGET.Month03<>SOURCE.Month03
				OR TARGET.Month04<>SOURCE.Month04
				OR TARGET.Month05<>SOURCE.Month05
				OR TARGET.Month06<>SOURCE.Month06
				OR TARGET.Month07<>SOURCE.Month07
				OR TARGET.Month08<>SOURCE.Month08
				OR TARGET.Month09<>SOURCE.Month09
				OR TARGET.Month10<>SOURCE.Month10
				OR TARGET.Month11<>SOURCE.Month11
				OR TARGET.Month12<>SOURCE.Month12
			)
		    THEN 
				UPDATE 
				SET TARGET.Month01=SOURCE.Month01,
					TARGET.Month02=SOURCE.Month02,
					TARGET.Month03=SOURCE.Month03,
					TARGET.Month04=SOURCE.Month04,
					TARGET.Month05=SOURCE.Month05,
					TARGET.Month06=SOURCE.Month06,
					TARGET.Month07=SOURCE.Month07,
					TARGET.Month08=SOURCE.Month08,
					TARGET.Month09=SOURCE.Month09,
					TARGET.Month10=SOURCE.Month10,
					TARGET.Month11=SOURCE.Month11,
					TARGET.Month12=SOURCE.Month12,
					TARGET.HistoryItemGUID = @higuid,
					TARGET.TransactionID = -100
			WHEN 
				NOT MATCHED BY SOURCE 
				AND TARGET.TransactionID = -100
		    THEN DELETE
		; -- end merge
	; -- end with
	
--------------------------------------------------------------------------------------------------
-- Invalidate department models
--------------------------------------------------------------------------------------------------

--disable cache for plans
	select @planRefreshList = 'PlanGUID in (''' + dbo.straggr(cast(dep.MemberGUID as nvarchar(36)), ''',''', '') + ''')'
	from #DepartmentsCache dep
	
	if (@planRefreshList <> '') 
	
	begin
	
	exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause = @planRefreshList,@isDebugOnly = 0, @source = 'Roster Transfer'

	end
--------------------------------------------------------------------------------------------------
-- Clean-up
--------------------------------------------------------------------------------------------------
	DROP TABLE #RosterAggregateInitial
	DROP TABLE #RosterAggregate
	DROP TABLE #RosterAggregateNoPCGInitial
	DROP TABLE #RosterAggregateNoPayCodeGroup
	DROP TABLE #Departments
	DROP TABLE #DepartmentsCache
	DROP TABLE #JobCodes
	DROP TABLE #JobCodeDept

END
GO


---------------------------------------------

-- ob.procSLReimbursementRefreshGrossChargesfromDeptBudgets
/************************************************************
** Author: blewis
** Create Date: 2015-04-23
** Description: Samples Gross Charges from Depts to Severice Line Reimbursement
** Last Modified: 2015-04-31
** GM Release: 2015.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
**  
*************************************************************/

CREATE PROC [ob].[procSLReimbursementRefreshGrossChargesfromDeptBudgets]
as

DECLARE @HIGuid as Nvarchar(36) = newid()
EXEC [dbo].[procLogHistory] @username ='StrataUser'  ,@desc ='procSLReimbursementRefreshGrossChargesfromDeptBudgets'  ,@cnt =0  ,@higuid =@HIGuid

--Refresh Charge Master Table
exec [clientob].[procFactChargeMasterRefresh] 

--Delete Stale Values
DELETE FROM [clientob].[FactServiceLineRevenue]
WHERE RowID IN(
		SELECT 
			RowID
		FROM [clientob].[FactServiceLineRevenue] FSLR
		WHERE FSLR.PayorID=0 AND FSLR.PayorGroupID=0 AND FSLR.OBForecastDetailID=38 --GROSS CHARGES
		AND NOT EXISTS(SELECT 1 FROM [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL WHERE
			VGCSL.DataTypeID=FSLR.DataTypeID 
			AND VGCSL.FiscalYearID=FSLR.FiscalYearID 
			AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID 
			AND VGCSL.PayorID=FSLR.PayorID
			AND VGCSL.PayorGroupID=FSLR.PayorGroupID 
			AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID 
			AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID
			AND VGCSL.TimeClassID=FSLR.TimeClassID
			AND VGCSL.UnitTypeID=FSLR.UnitTypeID)
				)

--Update Existing Values
UPDATE FSLR
SET Month01=VGCSL.Month01,
	Month02=VGCSL.Month02,
	Month03=VGCSL.Month03,
	Month04=VGCSL.Month04,
	Month05=VGCSL.Month05,
	Month06=VGCSL.Month06,
	Month07=VGCSL.Month07,
	Month08=VGCSL.Month08,
	Month09=VGCSL.Month09,
	Month10=VGCSL.Month10,
	Month11=VGCSL.Month11,
	Month12=VGCSL.Month12
FROM [clientob].[FactServiceLineRevenue] FSLR
INNER join [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL on 
	VGCSL.DataTypeID=FSLR.DataTypeID 
	AND VGCSL.FiscalYearID=FSLR.FiscalYearID 
	AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID 
	AND VGCSL.PayorID=FSLR.PayorID
	AND VGCSL.PayorGroupID=FSLR.PayorGroupID 
	AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID 
	AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID
	AND VGCSL.TimeClassID=FSLR.TimeClassID
	AND VGCSL.UnitTypeID=FSLR.UnitTypeID
WHERE
	FSLR.Month01 <> VGCSL.Month01 OR
	FSLR.Month02 <> VGCSL.Month02 OR
	FSLR.Month03 <> VGCSL.Month03 OR
	FSLR.Month04 <> VGCSL.Month04 OR
	FSLR.Month05 <> VGCSL.Month05 OR
	FSLR.Month06 <> VGCSL.Month06 OR
	FSLR.Month07 <> VGCSL.Month07 OR
	FSLR.Month08 <> VGCSL.Month08 OR
	FSLR.Month09 <> VGCSL.Month09 OR
	FSLR.Month10 <> VGCSL.Month10 OR
	FSLR.Month11 <> VGCSL.Month11 OR
	FSLR.Month12 <> VGCSL.Month12 
	
--Insert New Rows
INSERT INTO [clientob].[FactServiceLineRevenue]
([DataTypeID], [FiscalYearID], [ModelingServiceLineID], [PayorID], [PayorGroupID], [OBForecastDetailID], [OBServiceLinePlanID], [TimeClassID], [UnitTypeID], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12], [Yearly], [YTD], [IsDeleted], [HistoryItemGUID], [TransactionID])
	SELECT 
	[DataTypeID]
	, [FiscalYearID]
	, [ModelingServiceLineID]
	, [PayorID]
	, [PayorGroupID]
	, [OBForecastDetailID]
	, [OBServiceLinePlanID]
	, [TimeClassID]
	, [UnitTypeID]
	, [Month01]
	, [Month02]
	, [Month03]
	, [Month04]
	, [Month05]
	, [Month06]
	, [Month07]
	, [Month08]
	, [Month09]
	, [Month10]
	, [Month11]
	, [Month12]
	, 0 as [Yearly]
	, 0 AS [YTD]
	, 0 AS [IsDeleted]
	, @HIGuid as [HistoryItemGUID]
	, 0 as [TransactionID]
FROM [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL
	WHERE NOT(
			VGCSL.Month01 = 0 AND
			VGCSL.Month02 = 0 AND
			VGCSL.Month03 = 0 AND
			VGCSL.Month04 = 0 AND
			VGCSL.Month05 = 0 AND
			VGCSL.Month06 = 0 AND
			VGCSL.Month07 = 0 AND
			VGCSL.Month08 = 0 AND
			VGCSL.Month09 = 0 AND
			VGCSL.Month10 = 0 AND
			VGCSL.Month11 = 0 AND
			VGCSL.Month12 = 0)
		AND NOT EXISTS(SELECT 1 FROM [clientob].[FactServiceLineRevenue] FSLR WHERE
			VGCSL.DataTypeID=FSLR.DataTypeID 
			AND VGCSL.FiscalYearID=FSLR.FiscalYearID 
			AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID 
			AND VGCSL.PayorID=FSLR.PayorID
			AND VGCSL.PayorGroupID=FSLR.PayorGroupID 
			AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID 
			AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID
			AND VGCSL.TimeClassID=FSLR.TimeClassID
			AND VGCSL.UnitTypeID=FSLR.UnitTypeID)
GO


---------------------------------------------

-- ob.procSampleBudgetStampOffToIntTables
create PROC [ob].[procSampleBudgetStampOffToIntTables] AS
/* ************************************************************************************************************************
** Author: Mike Schmitz
** Create Date: 2014-09-19
** Description: Populates Budget Stamp-Off Data into the fw.int fact tables
** Last Modified: 2016-02-26
** GM Release: 2014.4
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
**	CID		Date		Author	WI		Description
**	1		2/24/15		MJS				Remove PayorCode and PayorGroupCode columns from the int.factserviceline insert
**	2		2016-02-26	cbb				update staffing data hours to use productive and non-productive
*************************************************************************************************************************/

declare @HistoryItemGUID uniqueidentifier = newid()

declare @year int = (select Setting+1 from DBSetting where Name = 'OB_Current_Year')

---------<<<<<<<<<<<<<<<< GL Data >>>>>>>>>>>>>>>>>>>>>>---------
DELETE FROM int.factGL
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactGL]
           ([DepartmentID]
           ,[DepartmentCode]
           ,[AccountID]
           ,[AccountCode]
           ,[FiscalYearID]
           ,[FiscalYearCode]
           ,[TimeClassID]
           ,[TimeClassCode]
           ,[FiscalMonthID]
           ,[FiscalMonthCode]
           ,[Value]
           ,[IsDeleted]
           ,[HistoryItemGUID])
	SELECT
		dep.DepartmentID 
		, dep.DepartmentCode 
		, acc.AccountID 
		, acc.AccountCode 
		, BudgetedData.FiscalYearID 
		, BudgetedData.FiscalYearID as FiscalYearCode
		, tc.TimeClassID
		, tc.TimeClassCode
		, fm.FiscalMonthID 
		, fm.FiscalMonthCode 
		, acc.inversion*Value as Value
		, '0' as IsDeleted
		, @HistoryItemGUID as HistoryItemGUID
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactAccountBudgetStampOff] fac
			WHERE fac.UnitTypeID = 34 --Dollars only
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID 
	INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	WHERE BudgetedData.Value <> 0
	
	
---------<<<<<<<<<<<<<<<< Department Stats Data >>>>>>>>>>>>>>>>>>>>>>---------
DELETE FROM int.factStatistic
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactStatistic]
           ([DepartmentID]
           ,[DepartmentCode]
           ,[AccountID]
           ,[AccountCode]
           ,[FiscalYearID]
           ,[FiscalYearCode]
           ,[TimeClassID]
           ,[TimeClassCode]
           ,[FiscalMonthID]
           ,[FiscalMonthCode]
           ,[Value]
           ,[IsDeleted]
           ,[HistoryItemGUID])
	SELECT
		  dep.DepartmentID 
		, dep.DepartmentCode 
		, acc.AccountID 
		, acc.AccountCode 
		, BudgetedData.FiscalYearID 
		, BudgetedData.FiscalYearID as FiscalYearCode
		, tc.TimeClassID
		, tc.TimeClassCode
		, fm.FiscalMonthID 
		, fm.FiscalMonthCode 
		, acc.inversion*Value as Value
		, '0' as IsDeleted
		, @HistoryItemGUID as HistoryItemGUID
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactAccountBudgetStampOff] fac
			WHERE fac.UnitTypeID = 140 --Volumes only
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID 
	INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	WHERE BudgetedData.Value <> 0
	
	
---------<<<<<<<<<<<<<<<< Global Stats Data >>>>>>>>>>>>>>>>>>>>>>---------	
DELETE FROM int.FactGlobalStatistics
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactGlobalStatistics] (
		  EntityID
		, EntityCode
		, DepartmentID
		, DepartmentCode
		, AccountID
		, AccountCode
		, FiscalYearID
		, FiscalYearCode
		, TimeClassID
		, TimeClassCode
		, FiscalMonthID
		, FiscalMonthCode
		, Value
		, IsDeleted
		, HistoryItemGUID
		)
	SELECT
		  ent.EntityID
		, ent.Code as 'EntityCode'
		, '0' as DepartmentID
		, '0' as DepartmentCode
		, acc.AccountID 
		, acc.AccountCode 
		, BudgetedData.FiscalYearID 
		, BudgetedData.FiscalYearID as FiscalYearCode
		, tc.TimeClassID
		, tc.TimeClassCode
		, fm.FiscalMonthID 
		, fm.FiscalMonthCode 
		, acc.inversion*Value as Value
		, '0' as IsDeleted
		, @HistoryItemGUID as HistoryItemGUID
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactGlobalStatisticsBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [ob].[DimOBGlobalStatistics] gs on gs.OBGlobalStatisticID = BudgetedData.OBGlobalStatisticID
	INNER JOIN fw.DimAccount acc on acc.AccountID = GS.AccountID 
	INNER JOIN fw.DimDepartment dep on dep.DepartmentID = GS.DepartmentID
	INNER JOIN ob.DimOBGlobalStatisticsPlan GSP on GSP.OBGlobalStatisticsPlanID = BudgetedData.OBGlobalStatisticsPlanID
	INNER JOIN fw.DimEntity ent on GSP.EntityID = ent.EntityID
	INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	WHERE gs.DepartmentID = 0 AND BudgetedData.Value <> 0
	
	
---------<<<<<<<<<<<<<<<< Staffing Data >>>>>>>>>>>>>>>>>>>>>>---------
DELETE FROM int.FactStaffing
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactStaffing] (
		DepartmentID 
		, DepartmentCode 
		, JobCodeID 
		, JobCode 
		, PayCodeID 
		, PayCode 
		, FiscalYearID 
		, FiscalYearCode
		, TimeClassID
		, TimeClassCode
		, UnitTypeID 
		, UnitType
		, FiscalMonthID 
		, FiscalMonthCode
		, Value
		, IsDeleted
		, HistoryItemGUID
		, EmployeeID 
		, EmployeeCode)
	SELECT
		dep.DepartmentID 
		, dep.DepartmentCode 
		, jc.JobCodeID 
		, jc.JobCode 
		, pc.PayCodeID 
		, pc.PayCode 
		, BudgetedData.FiscalYearID 
		, BudgetedData.FiscalYearID as FiscalYearCode
		, tc.TimeClassID
		, tc.TimeClassCode
-- CID 2 Begin
		, case 
			when ut.UnitTypeID = 34
				then 34
			else 51
			end as UnitTypeID
		, case
			when ut.Name ='Dollars'
				then 'Dollars'
			else 'Hours'
			end as UnitType
-- CID 2 End
		, fm.FiscalMonthID 
		, fm.FiscalMonthCode
		, Value as Value
		, '0' as IsDeleted
		, @HistoryItemGUID as HistoryItemGUID
		, '0' as EmployeeID 
		, '0' as EmployeeCode
	FROM (
		SELECT * 
		FROM ( 
			SELECT *
			FROM [clientob].[FactStaffingPCBudgetStampOff] fac
			) EXPORTDATA   
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = BudgetedData.JobCodeID 
	INNER JOIN [ob].[DimDepartmentalBudget] budget on budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = budget.DepartmentID 
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = BudgetedData.PayCodeGroupID
	INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
	INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
	WHERE 1=1
		and ut.UnitTypeID IN ('34','146','148') -- CID 2
		AND BudgetedData.Value <> 0 
		and PCG.PayCodeGroupID<>0	-- CID 2

---------<<<<<<<<<<<<<<<< CDM Data >>>>>>>>>>>>>>>>>>>>>>---------
DELETE FROM int.FactCDM
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactCDM] (
		DepartmentID,
		DepartmentCode,
		ChargeCodeID,
		ChargeCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		FiscalMonthID,
		FiscalMonthCode,
		PatientClassID,
		PatientClassCode,
		ServiceLineID,
		ServiceLine,
		AgeCohortID,
		AgeCohort,
		MedicalSurgicalID,
		MedSurg,
		UnitTypeID,
		UnitType,
		Value,
		IsDeleted,
		HistoryItemGUID)
	SELECT
		DEP.DepartmentID,
		DEP.DepartmentCode,
		CC.ChargeCodeID,
		CC.ChargeCode,
		BudgetedData.FiscalYearID,
		BudgetedData.FiscalYearID AS FiscalYearCode,
		TC.TimeClassID,
		TC.TimeClassCode,
		FM.FiscalMonthID,
		FM.FiscalMonthCode,
		PAT.PatientClassID,
		PAT.Code as 'PatientClassCode',
		'0' as ServiceLineID,
		'' as ServiceLine,
		'0' as AgeCohortID,
		'' as AgeCohort,
		'0' as MedicalSurgicalID,
		'' as MedSurg,
		UT.UnitTypeID,
		UT.Name as 'UnitType',
		Value
		,'0' as IsDeleted
		,@HistoryItemGUID as HistoryItemGUID
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactCDMBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
	INNER JOIN [ob].[DimDepartmentalBudget] Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = Budget.DepartmentID 
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
	WHERE BudgetedData.Value <> 0


---------<<<<<<<<<<<<<<<< Service Line Data >>>>>>>>>>>>>>>>>>>>>>---------
DELETE FROM int.FactServiceLine
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactServiceLine] (
		EntityID,
		EntityCode,
		PatientClassID,
		PatientClassCode,
		ServiceLineID,
		ServiceLine,
		AgeCohortID,
		AgeCohort,
		MedicalSurgicalID,
		MedSurg,
		PayorID,
		PayorGroupID,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		FiscalMonthID,
		FiscalMonthCode,
		OBForecastDetailID,
		ForecastDetail,
		Value,
		IsDeleted,
		HistoryItemGUID)
	SELECT
		E.EntityID,
		E.Code as 'EntityCode',
		PAT.PatientClassID,
		PAT.Code as 'PatientClassCode',
		SL.ServiceLineID,
		SL.Code as 'ServiceLineCode',
		AGE.AgeCohortID,
		AGE.Code as 'AgeCohort',
		MED.MedicalSurgicalID,
		MED.Code as 'MedSurg',
		PAY.PayorID,
		PAYG.PayorGroupID,
		BudgetedData.FiscalYearID,
		BudgetedData.FiscalYearID AS FiscalYearCode,
		TC.TimeClassID,
		TC.TimeClassCode,
		FM.FiscalMonthID,
		FM.FiscalMonthCode,
		FD.OBForecastDetailID,
		FD.Code as 'ForecastDetail',
		Value
		,'0' as IsDeleted
		,@HistoryItemGUID as HistoryItemGUID
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactServiceLineBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = BudgetedData.ModelingServiceLineID
	INNER JOIN [fw].[DimServiceLine] SL ON MSL.ServiceLineID = SL.ServiceLineID
	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = MSL.PatientClassID
	INNER JOIN [fw].[DimAgeCohort] AGE ON AGE.AgeCohortID = MSL.AgeCohortID
	INNER JOIN [fw].[DimMedicalSurgical] MED ON MED.MedicalSurgicalID = MSL.MedicalSurgicalID
	INNER JOIN [ob].[DimOBServiceLinePlan] P ON P.OBServiceLinePlanID = BudgetedData.OBServiceLinePlanID
	INNER JOIN [fw].[DimEntity] E on E.EntityID = P.EntityID
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
	INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID=0
	INNER JOIN [fw].[DimPayorGroup] PAYG ON PAYG.PayorGroupID=0
	WHERE BudgetedData.Value <> 0


---------<<<<<<<<<<<<<<<< Payor Data >>>>>>>>>>>>>>>>>>>>>>---------	
DELETE FROM int.FactOBPayor
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactOBPayor] (
		OBReimbursementPlanID,
		ReimbursementPlan,
		PatientClassID,
		PatientClassCode,
		PayorID,
		PayorCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		FiscalMonthID,
		FiscalMonthCode,
		OBForecastDetailID,
		OBForecastDetailCode,
		CareSettingID,
		CareSettingCode,
		Value,
		IsDeleted,
		HistoryItemGUID)
	SELECT
		P.OBReimbursementPlanID,
		P.Name as 'ReimbursementPlan',
		PAT.PatientClassID,
		PAT.Code as 'PatientClassCode',
		PAY.PayorID,
		PAY.PayorCode,
		BudgetedData.FiscalYearID,
		BudgetedData.FiscalYearID as 'FiscalYearCode',
		TC.TimeClassID,
		TC.TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		FD.OBForecastDetailID,
		FD.Code as 'OBForecastDetail',
		C.CareSettingID,
		C.Code as 'CareSettingCode',
		Value
		,'0' as IsDeleted
		,@HistoryItemGUID as 'HistoryItemGUID'
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactReimbursementBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID
	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID
	INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID
	INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID = BudgetedData.PayorID
	INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
	WHERE BudgetedData.Value <> 0

	
---------<<<<<<<<<<<<<<<< Payor Group Data >>>>>>>>>>>>>>>>>>>>>>---------	
DELETE FROM int.FactOBPayorGroup
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactOBPayorGroup] (
		OBReimbursementPlanID,
		ReimbursementPlan,
		PatientClassID,
		PatientClassCode,
		PayorGroupID,
		PayorGroupCode,
		FiscalYearID,
		FiscalYearCode,
		TimeClassID,
		TimeClassCode,
		FiscalMonthID,
		FiscalMonthCode,
		OBForecastDetailID,
		OBForecastDetailCode,
		CareSettingID,
		CareSettingCode,
		Value,
		IsDeleted,
		HistoryItemGUID)
	SELECT
		P.OBReimbursementPlanID,
		P.Name as 'ReimbursementPlan',
		PAT.PatientClassID,
		PAT.Code as 'PatientClassCode',
		PAY.PayorGroupID,
		PAY.PayorGroupCode,
		BudgetedData.FiscalYearID,
		BudgetedData.FiscalYearID as 'FiscalYearCode',
		TC.TimeClassID,
		TC.TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		FD.OBForecastDetailID,
		FD.Code as 'OBForecastDetail',
		C.CareSettingID,
		C.Code as 'CareSettingCode',
		Value
		,'0' as IsDeleted
		,@HistoryItemGUID as 'HistoryItemGUID'
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactReimbursementBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID
	INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID
	INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID
	INNER JOIN [fw].[DimPayorGroup] PAY ON PAY.PayorGroupID = BudgetedData.PayorGroupID
	INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
	WHERE BudgetedData.Value <> 0

	
---------<<<<<<<<<<<<<<<< Provider Data >>>>>>>>>>>>>>>>>>>>>>---------		
DELETE FROM int.FactImportProvider
WHERE FiscalYearID = @year and TimeClassID = 2

INSERT INTO [int].[FactImportProvider] (
		DepartmentID
		, DepartmentCode
		, ProviderID
		, ProviderCode
		, FiscalYearID
		, FiscalYearCode
		, TimeClassID
		, TimeClassCode
		, FiscalMonthID
		, FiscalMonthCode
		, OBForecastDetailID
		, AccountRollup
		, Value
		, IsDeleted
		, HistoryItemGUID
		)
	SELECT
		D.DepartmentID
		, D.DepartmentCode
		, PRO.ProviderID
		, PRO.ProviderCode
		, BudgetedData.FiscalYearID
		, BudgetedData.FiscalYearID as 'FiscalYearCode'
		, TC.TimeClassID
		, TC.TimeClassCode
		, FM.FiscalMonthID
		, FM.FiscalMonthCode
		, FD.OBForecastDetailID
		, FD.Name as 'AccountRollup'
		, Value
		,'0' as IsDeleted
		,@HistoryItemGUID as 'HistoryItemGUID'
	FROM (
		SELECT *
		FROM (
		 	SELECT *
			FROM [clientob].[FactProviderBudgetStampOff] fac
			) EXPORTDATA 
		UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT 
	) BudgetedData
	INNER JOIN [fw].[DimProvider] PRO ON PRO.ProviderID = BudgetedData.ProviderID
	INNER JOIN [ob].[DimDepartmentalBudget] P ON P.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID
	INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = P.DepartmentID
	INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID 
	INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode
	INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID
	WHERE BudgetedData.Value <> 0
	
exec procLogScript 'Sample Budget Stamp-Off to int tables' , @HistoryItemGUID output
GO


---------------------------------------------

-- ob.procSampleOBSLReimbursementandRunFillins
Create Proc [ob].[procSampleOBSLReimbursementandRunFillins] as
/************************************************************
** Author: Bart Lewis
** Create Date: 2015-06-17
** Description: Sample and Run fillins for OB SL Reimbursement Model
** Last Modified: 2015-06-17
** GM Release: 2015.3
**************************************************************
** Change History
**************************************************************
** CID	Date		Author		WI		Description
** 1	
*************************************************************/

exec [ob].[procSampleOBServiceLineRevenue] @PlanGUIDlist =''  
exec [ob].[procSampleServiceLineGLDeductionsCharityBadDebt]
exec [dbo].[procTERefreshFillins] @planTypeGUID ='957dd809-6299-4ec2-81fc-5452df805e8e'  ,@modelTemplateGUID ='f50d79a2-d0b8-4d31-8bc0-1350ea81c46a'  ,@placeholderSectionGUIDList =''  ,@IsDebugOnly = 0;
GO


---------------------------------------------

-- ob.procSampleOBServiceLineRevenue
/************************************************************
** Author: Bart Lewis
** Create Date: 11/18/2014
** Description: Rolling Service Line Revenue Sampling Proc
** Last Modified: 11/18/2014
** GM Release: 2015.2.1
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 
**
*************************************************************/

CREATE proc [ob].[procSampleOBServiceLineRevenue] 
@PlanGUIDlist as nvarchar(max)
as

--declare @PlanGUIDlist as nvarchar(max)
declare @isBackingUp bit
declare @isUpdatingExisting bit
declare @isClearingEntireTarget bit
declare @isInsertingNew bit
declare @isShowingAggResult bit
declare @isShowingSampleData bit
declare @targetTableName varchar(64)
declare @isClearingTempTables bit
declare @isViewingTarget bit
declare @isDisablingTriggers bit
declare @isInvalidatingModelWorkbookCache bit

--set @PlanGUIDlist ='00000000-0000-0000-0000-000000000000' 
set @isViewingTarget =0
set @isShowingSampleData = 0
set @isClearingEntireTarget = 1 -- Custom Delete
set @isBackingUp = 1
set @isShowingAggResult = 0
set @isInsertingNew = 1
set @isUpdatingExisting = 1
set @targetTableName = 'clientob.FactServiceLineRevenue'
set @isClearingTempTables = 1
set @isDisablingTriggers = 1 -- prevent history item entry creation
set @isInvalidatingModelWorkbookCache = 1 


declare @backupTableName varchar(1000)
set @backupTableName = 'temptablebackups.dbo.' + REPLACE(REPLACE(cast(DB_NAME() as varchar(32)),'.','_'),' ','_') + '_' + REPLACE(@targetTableName,'.','_') + cast(year(getdate()) as varchar(4)) + '_' + cast(month(getdate()) as varchar(4)) + '_' + cast(day(getdate()) as varchar(4)) + '_' + datename(hh,getdate()) + '_' + datename(mi,getdate()) + '_' + datename(ss,getdate()) + '_' + datename(ms,getdate()) + '_' + datename(ns,getdate())


--******************************************************************************************
--******************************************************************************************
--				Logging
--*******************************************************************************************
--*******************************************************************************************
declare @higuid uniqueidentifier
declare @desc nvarchar(4000)

set @desc = 'Sampling into ' + @targetTableName
set @desc = @desc + ', Inserting=' + cast(@isInsertingNew as varchar(1))
set @desc = @desc + ', Clearing=' + cast(@isClearingEntireTarget as varchar(1))
set @desc = @desc + ', Updating=' + cast(@isUpdatingExisting as varchar(1))
set @desc = @desc + ', BackingUp=' + cast(@isBackingUp as varchar(1))
set @desc = @desc + ', BackupTable=' + @backupTableName
print @desc
exec procLogScript @desc , @higuid output
print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36))

	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'Temptable') AND type = (N'U'))
	drop table TempTable
	
	if (@PlanGUIDlist='00000000-0000-0000-0000-000000000000' OR @PlanGUIDlist='')
	begin
		select 
			MemberGUID,
			OBServiceLinePlanID
		into TempTable
		from 
			[ob].[DimOBServiceLinePlan]
	end
	else
	begin
		select 
			MemberGUID,
			OBServiceLinePlanID
		into TempTable
		from 
			[ob].[DimOBServiceLinePlan] where MemberGUID in (select c.guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') c)
	end


--******************************************************************************************
--******************************************************************************************
print 'Sampling to temp table...'
--*******************************************************************************************
--*******************************************************************************************

	SELECT --~FQ_TOP~
		 source.DataTypeID
		 , source.FiscalYearID
		 , source.ModelingServiceLineID
		 , source.PayorID
		 , source.PayorGroupID
		 , source.OBForecastDetailID
		 , source.OBServiceLinePlanID
		 , source.TimeClassID
		 , source.UnitTypeID
		 ,	source.Month01
		 ,	source.Month02
		 ,	source.Month03
		 ,	source.Month04
		 ,	source.Month05
		 , 	source.Month06
		 ,	source.Month07
		 ,	source.Month08
		 , 	source.Month09
		 ,	source.Month10
		 ,	source.Month11
		 ,	source.Month12
		into #SampleData
	FROM
	[ob].[viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue] source
	WHERE
		not(
		source.Month01 = 0 and
		source.Month02 = 0 and
		source.Month03 = 0 and
		source.Month04 = 0 and
		source.Month05 = 0 and
		source.Month06 = 0 and
		source.Month07 = 0 and
		source.Month08 = 0 and
		source.Month09 = 0 and
		source.Month10 = 0 and
		source.Month11 = 0 and
		source.Month12 = 0)
		and source.OBServiceLinePlanID <> 0
		and source.OBServiceLinePlanID in (select t.OBServiceLinePlanID from TempTable t)
		----~SourceFilter~





	if @isShowingSampleData = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Showing Sample Data...'
		--*******************************************************************************************
		--*******************************************************************************************

		select top 100 * from #Sampledata
	end

	if @isBackingUp = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Backing up target table...'
		--*******************************************************************************************
		--*******************************************************************************************

		declare @sql varchar(max)
		set @sql = 'select * into ' + @backupTableName + ' from ' + @targetTableName
		exec (@sql)
	end


	if @isDisablingTriggers = 1 begin

	declare @sql2 varchar(max)
	set @sql2 = 'ALTER TABLE '+ @targetTableName + ' DISABLE TRIGGER ALL'
	exec (@sql2)

	end


	begin tran
	print 'Transaction Started'


	if @isClearingEntireTarget = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Clearing entire target...'
		--*******************************************************************************************
		--*******************************************************************************************
			delete
			--BEGIN TARGET TABLE NAME 
			--select * 
			from [clientob].[FactServiceLineRevenue]
			--END TARGET TABLE NAME 
			where 
			ROWID in (select la.ROWID from [clientob].[FactServiceLineRevenue] la
			inner join [ob].[DimOBServiceLinePlan] lrp on la.OBServiceLinePlanID=lrp.OBServiceLinePlanID --and lrp.IsDeleted=0
			where --la.FiscalYearID = Coalesce(@TargetedYearID, FiscalYearID) And la.TimeClassID= Coalesce(@TargetedTimeclassID, TimeClassID)	and 
			la.OBServiceLinePlanID in (select t.OBServiceLinePlanID from TempTable t)
			and la.DataTypeid=4--'Input' 
			)



		if @@error <> 0 begin
			print 'Transaction Rolled Back'
			rollback
			return
		end	
	end



	--******************************************************************************************
	--******************************************************************************************
	print 'Aggregating to mapping key level...'
	--*******************************************************************************************
	--*******************************************************************************************

	select
		
		--BEGIN INSERT TARGET KEY COLUMNS HERE
			 DataTypeID
			 , FiscalYearID
			 , ModelingServiceLineID
			 , PayorID
			 , PayorGroupID
			 , OBForecastDetailID
			 , OBServiceLinePlanID
			 , TimeClassID
			 , UnitTypeID		
		 --END INSERT TARGET KEY COLUMNS HERE

		--BEGIN INSERT TARGET VALUE COLUMNS HERE
			, SUM(Month01) as Month01
			, SUM(Month02) as Month02
			, SUM(Month03) as Month03
			, SUM(Month04) as Month04
			, SUM(Month05) as Month05
			, SUM(Month06) as Month06
			, SUM(Month07) as Month07
			, SUM(Month08) as Month08
			, SUM(Month09) as Month09
			, SUM(Month10) as Month10
			, SUM(Month11) as Month11
			, SUM(Month12) as Month12
		--END INSERT TARGET VALUE COLUMNS HERE
		
		, @higuid as HistoryItemGUID
		into #AggSampleData
	from
		#SampleData
	group by
		--INSERT TARGET COLUMNS HERE
			 DataTypeID
			 , FiscalYearID
			 , ModelingServiceLineID
			 , PayorID
			 , PayorGroupID
			 , OBForecastDetailID
			 , OBServiceLinePlanID
			 , TimeClassID
			 , UnitTypeID		
		--END INSERT TARGET COLUMNS HERE


	if @@error <> 0 begin
		print 'Transaction Rolled Back'
		rollback
		return
	end

	if @isShowingAggResult = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Showing agg result'
		--*******************************************************************************************
		--*******************************************************************************************
		select top 100 * from #AggSampleData
	end


	if @isUpdatingExisting =1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Updating existing rows...'
		--*******************************************************************************************
		--*******************************************************************************************
			update 
				targt
			set
				--BEGIN UPDATE TARGET VALUE COLUMNS
				targt.Month01 = source.Month01,
				targt.Month02 = source.Month02,
				targt.Month03 = source.Month03,
				targt.Month04 = source.Month04,
				targt.Month05 = source.Month05,
				targt.Month06 = source.Month06,
				targt.Month07 = source.Month07,
				targt.Month08 = source.Month08,
				targt.Month09 = source.Month09,
				targt.Month10 = source.Month10,
				targt.Month11 = source.Month11,
				targt.Month12 = source.Month12,
				--END UPDATE TARGET VALUE COLUMNS

				targt.historyitemguid = source.historyitemguid
			from 
				#AggSampleData source
				inner join [clientob].[FactServiceLineRevenue] targt on
				targt.OBServiceLinePlanID = source.OBServiceLinePlanID
				and targt.DataTypeID = source.DataTypeID
				and targt.ModelingServiceLineID = source.ModelingServiceLineID
				and targt.OBForecastDetailID = source.OBForecastDetailID
				and targt.PayorGroupID = source.PayorGroupID
				and targt.PayorID = source.PayorID 
				and targt.UnitTypeID = source.UnitTypeID
				and targt.TimeClassID = source.TimeClassID
				and targt.FiscalYearID = source.FiscalYearID
			where
				targt.Month01 <> source.Month01 and
				targt.Month02 <> source.Month02 and
				targt.Month03 <> source.Month03 and
				targt.Month04 <> source.Month04 and
				targt.Month05 <> source.Month05 and
				targt.Month06 <> source.Month06 and
				targt.Month07 <> source.Month07 and
				targt.Month08 <> source.Month08 and
				targt.Month09 <> source.Month09 and
				targt.Month10 <> source.Month10 and
				targt.Month11 <> source.Month11 and
				targt.Month12 <> source.Month12 
		
		if @@error <> 0 begin
			print 'Transaction Rolled Back'
			rollback
			return
		end
	end

	if @isInsertingNew = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Inserting missing rows...'
		--*******************************************************************************************
		--*******************************************************************************************

			insert into [clientob].[FactServiceLineRevenue]
			(
				--BEGIN INSERT TARGET KEY COLUMNS HERE
					 DataTypeID
					 , FiscalYearID
					 , ModelingServiceLineID
					 , PayorID
					 , PayorGroupID
					 , OBForecastDetailID
					 , OBServiceLinePlanID
					 , TimeClassID
					 , UnitTypeID		
				--END INSERT TARGET KEY COLUMNS HERE

				--BEGIN INSERT TARGET VALUE COLUMNS HERE
					, Month01
					, Month02
					, Month03
					, Month04
					, Month05
					, Month06
					, Month07
					, Month08
					, Month09
					, Month10
					, Month11
					, Month12
			--END INSERT TARGET VALUE COLUMNS HERE
				
				, HistoryItemGUID
			)
			select
				--BEGIN INSERT TARGET KEY COLUMNS HERE
				 DataTypeID
				 , FiscalYearID
				 , ModelingServiceLineID
				 , PayorID
				 , PayorGroupID
				 , OBForecastDetailID
				 , OBServiceLinePlanID
				 , TimeClassID
				 , UnitTypeID		
				--END INSERT TARGET KEY COLUMNS HERE

				--BEGIN INSERT TARGET VALUE COLUMNS HERE
					, Month01
					, Month02
					, Month03
					, Month04
					, Month05
					, Month06
					, Month07
					, Month08
					, Month09
					, Month10
					, Month11
					, Month12
				--END INSERT TARGET VALUE COLUMNS HERE
				
				, HistoryItemGUID
			from
				#AggSampleData source
			where not exists (
					select 1 from
						[clientob].[FactServiceLineRevenue] targt 
					where
					targt.OBServiceLinePlanID = source.OBServiceLinePlanID
					and targt.DataTypeID = source.DataTypeID
					and targt.ModelingServiceLineID = source.ModelingServiceLineID
					and targt.OBForecastDetailID = source.OBForecastDetailID
					and targt.PayorGroupID = source.PayorGroupID
					and targt.PayorID = source.PayorID 
					and targt.UnitTypeID = source.UnitTypeID
					and targt.TimeClassID = source.TimeClassID
					and targt.FiscalYearID = source.FiscalYearID)
		
		if @@error <> 0 begin
			print 'Transaction Rolled Back'
			rollback
			return
		end

	end

	--Drop temp Table
	drop table TempTable

	--Delete bad rows?
	if @@error = 0  begin
		print 'Transaction Committed'
		commit
	end	
	else begin
		print 'Transaction Rolled Back'
		rollback
	end



	if @isDisablingTriggers = 1 begin

	set @sql2 = 'ALTER TABLE '+ @targetTableName + ' ENABLE TRIGGER ALL'
	exec (@sql2)

	end


	if @isClearingTempTables = 1 begin
		--******************************************************************************************
		--******************************************************************************************
		print 'Clearing temp tables...'
		--*******************************************************************************************
		--*******************************************************************************************

		drop table #SampleData
		drop table #AggSampleData
	end

	if @isViewingTarget = 1 begin
		select top 100 * from [clientob].[FactServiceLineRevenue] where Month01 <> 0 and Month02 <> 0 and Month03 <> 0 and Month04 <> 0 and 
			Month05 <> 0 and Month06 <> 0 and Month07 <> 0 and Month08 <> 0 and 
			Month09 <> 0 and Month10 <> 0 and Month11 <> 0 and Month12 <> 0 and 
			Yearly<>0
	end

	if @isInvalidatingModelWorkbookCache = 1  
	begin
		if (@PlanGUIDlist='00000000-0000-0000-0000-000000000000')
		begin
			exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '957dd809-6299-4ec2-81fc-5452df805e8e', 'OB procSampleFactServiceLineRevenueMonthly'
		end else begin
			declare @invalidateWhere nvarchar(max)
			set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @PlanGUIDList + ''','',''))'
			exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'OB procSampleFactServiceLineRevenueMonthly'
		end
	end

RETURN
GO


---------------------------------------------

-- ob.procSampleServiceLineGLDeductionsCharityBadDebt
/************************************************************
** Author: blewis
** Create Date: 2015-05-20
** Description: Samples Charity and Bad Debt Data for SL Reimbursement
** Last Modified: 2015-05-20
** GM Release: 2015-05-20
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1
** 2
*************************************************************/

CREATE proc [ob].[procSampleServiceLineGLDeductionsCharityBadDebt]
as

-- Logging ************************************************************************
declare @higuid uniqueidentifier
exec procLogScript 'Sampling Charity and Bad Debt into clientob.FactServiceLineAccount' , @higuid output
print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36))

-- Backup ************************************************************************
declare @dbname nvarchar(1000) = (DB_Name())
exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineAccount', 'clientob'

-- Temp table ************************************************************************
select 	d.OBServiceLinePlanID,
		34 as UnitTypeID,
		f.TimeClassID,
		4 as DataTypeID,
		f.FiscalYearID,
		f.AccountID,
		SUM(f.ValueMonth01 * a.Inversion) as Month01, 
		SUM(f.ValueMonth02 * a.Inversion) as Month02, 
		SUM(f.ValueMonth03 * a.Inversion) as Month03,
		SUM(f.ValueMonth04 * a.Inversion) as Month04,
		sum(f.ValueMonth05 * a.Inversion) as Month05,
		SUM(f.ValueMonth06 * a.Inversion) as Month06,
		SUM(f.ValueMonth07 * a.Inversion) as Month07,
		SUM(f.ValueMonth08 * a.Inversion) as Month08,	
		SUM(f.ValueMonth09 * a.Inversion) as Month09,
		SUM(f.ValueMonth10 * a.Inversion) as Month10, 
		sum(f.ValueMonth11 * a.Inversion) as Month11,
		sum(f.ValueMonth12 * a.Inversion) as Month12,
		SUM(f.ValueYearly * a.Inversion) as Yearly
		into #SampleData
from 	[int].[viewFactGLPivoted] f
		inner join [ob].[DimDepartmentalBudget] db on f.DepartmentID=db.DepartmentID
		inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID and OBServiceLinePlanID<>0
		inner join [fw].[DimAccount] a on a.AccountID=f.AccountID
where	
		f.FiscalYearID>=(select Setting-1 from [dbo].[DBSetting] where Name='OB_Current_Year') and
		a.PatientClassID IN(Select distinct PatientClassID from [fw].[DimModelingServiceLine] where PatientClassID<>0) and
		a.OBAccountPHID in 
		(
		4,		--Deductions
		484,	--Deductions - Charity and Bad Debt
		481		--Deductions - Reimbursement
		)
group by 
	d.OBServiceLinePlanID
	,f.TimeClassID
	,f.FiscalYearID
	,f.AccountID

-- Remove old data ************************************************************************

	delete fct
	from
		[clientob].[FactServiceLineAccount] fct
		inner join [ob].[DimOBServiceLinePlan] pln on fct.OBServiceLinePlanID=pln.OBServiceLinePlanID
		inner join [data].[ScoreFillin_Account] sf on pln.MemberGUID=sf.ModelGUID
	where
		DataTypeID = (select DataTypeID from fw.DimDataType where globalid='Input')
		and 
		sf.AccountPHID in
		(
		4,		--Deductions
		484,	--Deductions - Charity and Bad Debt
		481		--Deductions - Reimbursement
		)
		

-- Aggregating ************************************************************************
declare @monthsLoaded int = clientob.getmonthsloaded()

select
		src.OBServiceLinePlanID,
		src.UnitTypeID,
		src.TimeClassID,
		src.DataTypeID,
		src.FiscalYearID,
		src.AccountID,
		SUM(src.Month01) as Month01, 
		SUM(src.Month02) as Month02, 
		SUM(src.Month03) as Month03,
		SUM(src.Month04) as Month04,
		sum(src.Month05) as Month05,
		SUM(src.Month06) as Month06,
		SUM(src.Month07) as Month07,
		SUM(src.Month08) as Month08,	
		SUM(src.Month09) as Month09,
		SUM(src.Month10) as Month10, 
		sum(src.Month11) as Month11,
		sum(src.Month12) as Month12,
		sum(src.Yearly) as Yearly,
		@monthsLoaded as MonthsLoaded,
		@higuid as HistoryItemGUID
	
into #AggSampleData
from
	#SampleData src
group by 
	src.OBServiceLinePlanID
	,src.UnitTypeID
	,src.TimeClassID
	,src.DataTypeID
	,src.FiscalYearID
	,src.AccountID

-- Update Existing ************************************************************************


update	ra
set 	ra.Month01=cons.Month01,
		ra.Month02=cons.Month02,
		ra.Month03=cons.Month03,
		ra.Month04=cons.Month04,
		ra.Month05=cons.Month05,
		ra.Month06=cons.Month06,
		ra.Month07=cons.Month07,
		ra.Month08=cons.Month08,
		ra.Month09=cons.Month09,
		ra.Month10=cons.Month10,
		ra.Month11=cons.Month11,
		ra.Month12=cons.Month12,
		ra.Yearly=cons.Yearly,
		ra.MonthsLoaded=cons.monthsloaded,
		ra.historyitemguid=cons.historyitemguid
from
	[clientob].[FactServiceLineAccount] ra 
	inner join #AggSampleData cons					
	ON	cons.OBServiceLinePlanID=ra.OBServiceLinePlanID 
		and cons.UnitTypeID=ra.UnitTypeID
		and cons.TimeClassID=ra.TimeClassID
		and cons.DataTypeID=ra.DataTypeID
		and cons.FiscalYearID=ra.FiscalYearID
		and cons.AccountID=ra.AccountID



-- Insert New ************************************************************************
insert into clientob.FactServiceLineAccount(
OBServiceLinePlanID, 
AccountID, 
FiscalYearID,
TimeClassID, 
UnitTypeID, 
DataTypeID, 
Month01, 
Month02, 
Month03, 
Month04, 
Month05, 
Month06, 
Month07, 
Month08, 
Month09, 
Month10, 
Month11, 
Month12, 
Yearly,
MonthsLoaded,
HistoryItemGUID
)
select
OBServiceLinePlanID, 
AccountID, 
FiscalYearID,
TimeClassID, 
UnitTypeID, 
DataTypeID, 
Month01, 
Month02, 
Month03, 
Month04, 
Month05, 
Month06, 
Month07, 
Month08, 
Month09, 
Month10, 
Month11, 
Month12, 
Yearly,
MonthsLoaded,
HistoryItemGUID
from
	#AggSampleData source
where not exists (
		select 1 from
			clientob.FactServiceLineAccount targt 
		where
		   source.OBServiceLinePlanID=targt.OBServiceLinePlanID 
		and source.UnitTypeID=targt.UnitTypeID
		and source.TimeClassID=targt.TimeClassID
		and source.DataTypeID=targt.DataTypeID
		and source.FiscalYearID=targt.FiscalYearID
		and source.AccountID=targt.AccountID
	
	)


-----------------------------------------------------
-------------------disable cache---------------------
-----------------------------------------------------
declare @PlanTypeguid as uniqueidentifier = (select top 1 plantypeguid from PlanType where GlobalID='OB Service Line')

exec procInvalidateModelWorkbookCacheByPlanType @PlanTypeguid, 'procSampleServiceLineGLDeductionsCharityBadDebt'

-- Clean up
drop table #SampleData
drop table #AggSampleData
GO


---------------------------------------------

-- ob.procSendCriticalExceptionNotifications
CREATE PROC [ob].[procSendCriticalExceptionNotifications]
AS

--@recipients_list should be a list of (;) separated e-mail addresses
Declare @recipients_list varchar(2000) = (Select Setting from [dbo].[DBSetting] where Name='OBCriticalExceptionNotificationList')

--Only send exception notifications when budget is Open
DECLARE @IsBudgetOpen BIT = CAST(IIF(EXISTS(SELECT TOP 1 1 FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status' AND [Value] <> '0'), 1, 0) AS BIT);

--Get DB FriendlyName
DECLARE @Client varchar(200) = (Select Setting from [dbo].[DBSetting] where Name='FORM_CLIENTNAME')

--Get Log In URL
DECLARE @LoginURL varchar(200) = (Select Setting from [dbo].[DBSetting] where Name='GENERAL_APPURL')

--Get Client Org Pin
DECLARE @OrgPIN NVARCHAR(4);
DECLARE @DatabaseGUID UNIQUEIDENTIFIER;
EXEC dbo.procSMCGetDatabaseGUID @ReturnVal=@DatabaseGUID OUTPUT;

DECLARE @SMCServer NVARCHAR(4000) = (SELECT TOP 1 REPLACE(REPLACE(Setting,'[',''),']','') FROM DBSetting WHERE Name='SMC_PRIMARY_SERVER')
DECLARE @SMCDatabase NVARCHAR(4000) = (SELECT TOP 1 REPLACE(REPLACE(Setting,'[',''),']','') FROM DBSetting WHERE Name='SMC_PRIMARY_DATABASE')

DECLARE @SMCSQL NVARCHAR(4000) = 'SELECT @OrgPIN_OUT=OrgPIN FROM [' + @SMCServer + '].[' + @SMCDatabase + '].[dbo].[viewDatabaseInfo] x WHERE x.DatabaseGUID=''' + CAST(@DatabaseGUID AS NVARCHAR(36)) + ''''
EXEC sp_executesql @SMCSQL,N'@OrgPIN_OUT NVARCHAR(4) OUTPUT',@OrgPIN_OUT=@OrgPIN OUTPUT;


if @recipients_list = ''
	begin
		print 'No recipients provided'
		return;
	end
	
if @IsBudgetOpen = 1
	begin

	declare @bodystr varchar(max)='';
	declare @dbsubject varchar(300);
	declare @exception_count int;
	DECLARE @xml NVARCHAR(MAX);


	select @exception_count=count(*)
	from [ob].[FactDepartmentBudgetExceptions] e
		inner join [ob].[DimOBExceptions] de on e.OBExceptionsID=de.OBExceptionsID
	where
		de.Severity like 'Critical%'
		and Acknowledged=0
		and IsDeleted=0;
		
	if @exception_count>0
		begin
			set @dbsubject='Alert from '+@@SERVERNAME+'.'+DB_NAME(); --set @bodystr=@bodystr+'# of Critical Exceptions = '+convert(varchar,@exception_count)

				SET @xml = CAST(( 
				Select Model AS 'td','',Severity AS 'td','', CountA AS 'td'
				From (
					--SCRIPT for Exceptions Counts
						--Dept
						select 'Deparment Budget' AS 'Model',de.Severity, count(*) as CountA
						from [ob].[FactDepartmentBudgetExceptions] be
						inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
						inner join [ob].[viewDimDepartmentalBudget] db on db.DepartmentalBudgetID=be.DepartmentalBudgetID and db.DepartmentalBudgetID<>0 
						where be.Acknowledged=0 and IsDeleted=0
						Group by de.Severity
						
						UNION ALL
						--Reimb
						select 'Reimbursement' AS 'Model',de.Severity, count(*) as CountA
						from [ob].[FactReimbursementExceptions] be
						inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
						inner join [ob].[viewDimOBReimbursementPlan] db on db.OBReimbursementPlanID=be.OBReimbursementPlanID and db.OBReimbursementPlanID<>0 
						where be.Acknowledged=0 and IsDeleted=0
						Group by de.Severity
						
						UNION ALL					
						--Global Stats
						select 'Global Stats' AS 'Model',de.Severity, count(*) as CountA
						from [ob].[FactGlobalStatisticExceptions] be
						inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
						inner join [ob].[viewDimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=be.OBGlobalStatisticsPlanID and db.OBGlobalStatisticsPlanID<>0 
						where be.Acknowledged=0 and db.IsDeleted=0
						Group by de.Severity
						
						UNION ALL					
						--Service Line
						select 'Service Line' AS 'Model',de.Severity, count(*) as CountA
						from [ob].[FactServiceLineExceptions] be
						inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
						inner join [ob].[viewDimOBServiceLinePlan] db on db.OBServiceLinePlanID=be.OBServiceLinePlanID and db.OBServiceLinePlanID<>0 
						where be.Acknowledged=0 and db.IsDeleted=0
						Group by de.Severity
					) SUB
			FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

			--Set Client Name, Org Pin, and URL
			SET @bodystr ='
			<html><body><H2>' + @Client + 'Org Pin:' + @OrgPIN + '</H2>
			<a href="'+ @LoginURL +'">Login to Database</a>
			<html><body><H3>Exception Count by Severity</H3>
			<table border = 1> 
			<tr>
			<th> PlanType </th> <th> Severity </th> <th> Count </th>' 
			
			SET @bodystr = @bodystr + @xml +'</table></body></html>'		


			SET @xml = CAST(( 
				--SCRIPT for Critical Data Loss
				Select Model AS 'td','', FullName AS 'td','', Name AS 'td','', Detail AS 'td'
				from (
					--Dept
					select 'Deparment Budget' AS Model,de.FullName, db.Name , be.Detail
					from [ob].[FactDepartmentBudgetExceptions] be
					inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
					inner join [ob].[viewDimDepartmentalBudget] db on db.DepartmentalBudgetID=be.DepartmentalBudgetID and db.DepartmentalBudgetID<>0 
					where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and IsDeleted=0
					
					UNION ALL
					--Reimb
					select 'Reimbursement' AS Model,de.FullName, db.Name , be.Detail
					from [ob].[FactReimbursementExceptions] be
					inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
					inner join [ob].[viewDimOBReimbursementPlan] db on db.OBReimbursementPlanID=be.OBReimbursementPlanID and db.OBReimbursementPlanID<>0 
					where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and IsDeleted=0

					UNION ALL
					--Global Stats
					select 'Global Stats' AS Model,de.FullName, db.Name , be.Detail
					from [ob].[FactGlobalStatisticExceptions] be
					inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
					inner join [ob].[viewDimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=be.OBGlobalStatisticsPlanID and db.OBGlobalStatisticsPlanID<>0 
					where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and DB.IsDeleted=0

					UNION ALL
					--Service Line
					select 'Service Line' AS Model,de.FullName, db.Name , be.Detail
					from [ob].[FactServiceLineExceptions] be
					inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID
					inner join [ob].[viewDimOBServiceLinePlan] db on db.OBServiceLinePlanID=be.OBServiceLinePlanID and db.OBServiceLinePlanID<>0 
					where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and DB.IsDeleted=0
				) SUB
			FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))


			SET @bodystr = @bodystr + '<html><body><H3>Critical - Data Loss</H3>
			<table border = 1> 
			<tr>
			<th> ModelType </th> <th> ExceptionType </th> <th> Department </th> <th> Detail </th>'    

			 
			SET @bodystr = @bodystr + @xml +'</table></body></html>'		
			
			EXEC msdb.dbo.sp_send_dbmail
			@profile_name = 'DatabaseMail',
			@recipients = @recipients_list,
			@body = @bodystr,
			@body_format ='HTML',
			@subject = @dbsubject;
	end
end
GO


---------------------------------------------

-- ob.procServiceLineVolumetoReimbursementSample
/************************************************************
** Author: blewis
** Create Date: 2014-08-11
** Description: Samples Volume from SL model to Reimbursement Model
** Last Modified: 2017-06-06
** GM Release: 2014.4
**************************************************************
** Change History
**************************************************************
** CID      Date       Author	WI			Description
** 1		9/2/2014		BJL	 				Remove the "Output" Filter on Datatype to allow historical Data from SL                 
** 2		3/6/2015		GJF					Skip invalidate for native modeling support
** 3		9/20/2016		GJF		B-12949	Add direct call to CDM sample at end, instead of bundling this proc in the custom script
** 4		6/6/2017		SRK		D-05890	Moved the proc that updates departmental budget models outside of the IF statement that is used only for Reimbursement
** 5`		10/12/2017	cbb		D-06496	added paramter for cdm sampling
*************************************************************/
CREATE proc [ob].[procServiceLineVolumetoReimbursementSample]
	@planGUIDList nvarchar(max)='',
	@IsCDMSampling bit = 1
as

-----------------------------CID 4----------------------------------------
	-- Sample CDM, which will trigger a partial refresh
	if @IsCDMSampling = 1
		begin
			exec [clientob].[procSampleCDMAll] @planGUIDList, 0;
		end
	
-----------------------------CID 4----------------------------------------	

	IF((select Max(OBServiceLinePrimaryVolumeAccountID) from [fw].[DimPatientClass]) = 0 ) Begin
		return
	End

	-- Temp plans ********************************************************************
	Create Table #Plans(OBServiceLinePlanID int, OBReimbursementPlanID int)

	if (len(@planGUIDList) = 0) begin
		-- if no plans provided, we will sample all plans
		insert into #Plans(OBServiceLinePlanID,OBReimbursementPlanID)
		select OBServiceLinePlanID, OBReimbursementPlanID
			from (SELECT DISTINCT
							MD.OBServiceLinePlanID
							, MD.OBReimbursementPlanID
							, SL.MemberGUID
							FROM 
								[fw].[DimDepartment] MD
							Inner join [ob].[DimOBServiceLinePlan] SL on md.OBServiceLinePlanID=SL.OBServiceLinePlanID
							WHERE MD.OBReimbursementPlanID<>0 AND MD.OBServiceLinePlanID<>0) P
	end
	else begin
		insert into #Plans(OBServiceLinePlanID, OBReimbursementPlanID)
		select 
			plandim.OBServiceLinePlanID
			, plandim.OBReimbursementPlanID
		from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') planguids
			inner join (SELECT DISTINCT
							MD.OBServiceLinePlanID
							, MD.OBReimbursementPlanID
							, SL.MemberGUID
							FROM 
								[fw].[DimDepartment] MD
							Inner join [ob].[DimOBServiceLinePlan] SL on md.OBServiceLinePlanID=SL.OBServiceLinePlanID
							WHERE MD.OBReimbursementPlanID<>0 AND MD.OBServiceLinePlanID<>0) plandim on planguids.guid = plandim.MemberGUID
	end

	-- Logging ************************************************************************
	declare @higuid uniqueidentifier
	exec procLogScript 'Sampling into clientob.FactReimbursementAccount' , @higuid output
	print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36))

	-- Backup ************************************************************************
	--declare @dbname nvarchar(1000) = (DB_Name())
	--exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccount', 'clientob'

	-- Temp table ************************************************************************
	select
	                        src.OBReimbursementPlanID,
	                        src.PatientReimbursementGroupID,
	                        src.UnitTypeID,
	                        src.TimeClassID,
	                        src.DataTypeID,
	                        src.FiscalYearID,
	                        src.AccountID,
	                        SUM(src.Month01) as Month01, 
	                        SUM(src.Month02) as Month02, 
	                        SUM(src.Month03) as Month03,
	                        SUM(src.Month04) as Month04,
	                        sum(src.Month05) as Month05,
	                        SUM(src.Month06) as Month06,
	                        SUM(src.Month07) as Month07,
	                        SUM(src.Month08) as Month08,        
	                        SUM(src.Month09) as Month09,
	                        SUM(src.Month10) as Month10, 
	                        sum(src.Month11) as Month11,
	                        sum(src.Month12) as Month12,
	                        SUM(src.Yearly) as Yearly
	                        into #SampleData
	from (
	            SELECT
	                        map.[OBReimbursementPlanID]
	                        , prg.PatientReimbursementGroupID
	                        , fs.[UnitTypeID]
	                        , fs.[TimeClassID]
	                        , 4 as [DataTypeID]
	                        , fs.[FiscalYearID]
	                        , pc.[OBServiceLinePrimaryVolumeAccountID] as [AccountID]
	                        , [Month01]
	                        , [Month02]
	                        , [Month03]
	                        , [Month04]
	                        , [Month05]
	                        , [Month06]
	                        , [Month07]
	                        , [Month08]
	                        , [Month09]
	                        , [Month10]
	                        , [Month11]
	                        , [Month12]
	                        , [Yearly]
	            FROM [clientob].[FactServiceLine] fs
	            INNER JOIN [fw].[DimModelingServiceLine] ms on fs.ModelingServiceLineID=ms.ModelingServiceLineID
				INNER JOIN [ob].[DimOBServiceLinePlan] sl ON fs.OBServiceLinePlanID=sl.OBServiceLinePlanID
				INNER JOIN #Plans map ON sl.OBServiceLinePlanID=map.OBServiceLinePlanID
	            INNER JOIN [ob].[DimOBForecastDetail] fd on fs.OBForecastDetailID=fd.OBForecastDetailID
	            INNER JOIN [fw].[DimPatientReimbursementGroup] prg on ms.PatientClassID=prg.PatientClassID and CareSettingID=0
				Inner Join [fw].[DimPatientClass] pc on prg.PatientClassID=pc.PatientClassID
	            Where 
				--==== BEGIN CID 1 ====
					--DataTypeID=3 and 
				--==== END CID 1 ====	
				
				prg.PatientReimbursementGroupID<>0 and pc.OBServiceLinePrimaryVolumeAccountID<>0 and fd.Name='Volume'
	) src
	group by src.OBReimbursementPlanID,src.PatientReimbursementGroupID,src.UnitTypeID,
	                        src.TimeClassID,src.DataTypeID,src.FiscalYearID,src.AccountID
	                        
	                     
	-- Remove old data ************************************************************************
	            delete fct
	            from
	                        [clientob].[FactReimbursementAccount] fct
	            where
	                        fct.RowID IN(
	                                    Select RowID 
	                                    from 
	                                                [clientob].[FactReimbursementAccount] fa
	                                                inner join #SampleData sd on fa.AccountID=sd.AccountID and fa.PatientReimbursementGroupID=sd.PatientReimbursementGroupID)
	-- Aggregating ************************************************************************
	declare @monthsLoaded int = clientob.getmonthsloaded()

	select
	                        src.OBReimbursementPlanID,
	                        src.PatientReimbursementGroupID,
	                        src.UnitTypeID,
	                        src.TimeClassID,
	                        src.DataTypeID,
	                        src.FiscalYearID,
	                        src.AccountID,
	                        SUM(src.Month01) as Month01, 
	                        SUM(src.Month02) as Month02, 
	                        SUM(src.Month03) as Month03,
	                        SUM(src.Month04) as Month04,
	                        sum(src.Month05) as Month05,
	                        SUM(src.Month06) as Month06,
	                        SUM(src.Month07) as Month07,
	                        SUM(src.Month08) as Month08,        
	                        SUM(src.Month09) as Month09,
	                        SUM(src.Month10) as Month10, 
	                        sum(src.Month11) as Month11,
	                        sum(src.Month12) as Month12,
	                        sum(src.Yearly) as Yearly,
	                        @monthsLoaded as MonthsLoaded,
	                        @higuid as HistoryItemGUID
	into #AggSampleData
	from
	            #SampleData src
	group by src.OBReimbursementPlanID,src.PatientReimbursementGroupID,src.UnitTypeID,
	                        src.TimeClassID,src.DataTypeID,src.FiscalYearID,src.AccountID
							



	-- Insert New ************************************************************************
	insert into clientob.FactReimbursementAccount(
	OBReimbursementPlanID, 
	AccountID, 
	FiscalYearID,
	PatientReimbursementGroupID,
	TimeClassID, 
	UnitTypeID, 
	DataTypeID, 
	Month01, 
	Month02, 
	Month03, 
	Month04, 
	Month05, 
	Month06, 
	Month07, 
	Month08, 
	Month09, 
	Month10, 
	Month11, 
	Month12, 
	Yearly,
	MonthsLoaded,
	HistoryItemGUID
	)
	select
	OBReimbursementPlanID, 
	AccountID, 
	FiscalYearID,
	PatientReimbursementGroupID,
	TimeClassID, 
	UnitTypeID, 
	DataTypeID, 
	Month01, 
	Month02, 
	Month03, 
	Month04, 
	Month05, 
	Month06, 
	Month07, 
	Month08, 
	Month09, 
	Month10, 
	Month11, 
	Month12, 
	Yearly,
	MonthsLoaded,
	HistoryItemGUID
	from
	            #AggSampleData source
	where not exists (
	                        select 1 from
	                                    clientob.FactReimbursementAccount targt 
	                        where
	                           source.OBReimbursementPlanID=targt.OBReimbursementPlanID 
	                        and source.PatientReimbursementGroupID=targt.PatientReimbursementGroupID
	                        and source.UnitTypeID=targt.UnitTypeID
	                        and source.TimeClassID=targt.TimeClassID
	                        and source.DataTypeID=targt.DataTypeID
	                        and source.FiscalYearID=targt.FiscalYearID
	                        and source.AccountID=targt.AccountID
	            
	            )
	                                                
	-- Clean up
	drop table #SampleData
	drop table #AggSampleData
	Drop table #Plans
GO


---------------------------------------------

-- ob.procTERefreshFillins_DepartmentalBudgetAll
create proc ob.procTERefreshFillins_DepartmentalBudgetAll
	@isDeleting bit = 0
as
	if (@isDeleting = 1) begin
		--delete existing fillins
		declare @deleteWhere nvarchar(max)
		select @deleteWhere = 'ModelGUID in(select x.PlanGUID from dbo.XPlan x where x.PlanTypeGUID = ''' + cast(PlanTypeGUID as nvarchar(36)) + ''' and x.IsDeletedPlan = 0)' from [dbo].[PlanType] where GlobalID = 'OB Departmental Budget'
		declare @deleteCount int
		select @deleteCount = count(*) from [dbo].[ScoreFillin] where ModelGUID in(select x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0)
		print 'Deleting...'
		exec [dbo].[procRollingDeleteOnTable] 'dbo', 'ScoreFillin', 'RowID', '[dbo].[ScoreFillin]', @deleteWhere, @deleteCount, 1, 0
		exec [dbo].[procScoreFillinTableRebuildAll]
		print 'Delete complete.'
	end
	
	--chunk refresh by plan
	declare @planguid uniqueidentifier
	select top 1 @planguid = x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0
	insert into [dbo].[FillinRefreshRequest] (PlanGUID) select x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0 and x.PlanGUID != @planguid
	exec [dbo].[procTERefreshFillinsByPlan] @planguid, '', 0
	print 'Task created.'
GO


---------------------------------------------

-- ob.procUpdateMonthsLoaded
CREATE proc ob.procUpdateMonthsLoaded as
/************************************************************
** Author: akowalski
** Create Date: 2014-04-10
** Description: Updates months data loaded on all dimensions and composite tables
** Last Modified: 2015-02-05
** GM Release: 2014.3
**************************************************************
** Change History
**************************************************************
** CID		Date		Author	WI		Description
** 1		2015-02-05	akozlovskyi		Excluded updating of deleted table DimOBAllocationsPlan
**
*************************************************************/

Declare @monthsloaded varchar(2) = cast(clientob.GetMonthsLoaded() as varchar(2))

-- Update plan dimensions
update [ob].[DimDepartmentalBudget] set MonthsLoaded=@monthsloaded
update [ob].[DimOBGlobalStatisticsPlan] set MonthsLoaded=@monthsloaded
update [ob].[DimOBReimbursementPlan] set MonthsLoaded=@monthsloaded
update [ob].[DimOBServiceLinePlan] set MonthsLoaded=@monthsloaded

-- Update composites
SET NOCOUNT ON;

	DECLARE @SCHEMA nvarchar(256)
	DECLARE @FactTableName nvarchar(256)
	DECLARE @SQL nvarchar(1024)
	DECLARE FactTableCursor CURSOR FOR 
	select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map') order by t.name
	open FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		if (dbo.ColumnExists(@SCHEMA,@FactTableName,'MonthsLoaded')=1)
		begin
		set @SQL = 'update ' + @SCHEMA + '.' + @FactTableName + ' set MonthsLoaded=' + @monthsloaded
		
	    --print @SQL
	    EXECUTE sp_executesql @SQL 
		end
	    FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor



RETURN
GO


---------------------------------------------

-- ob.procUpdateOBSectionPermissions
CREATE PROCEDURE [ob].[procUpdateOBSectionPermissions]
AS
BEGIN
	DECLARE @isBudgetOpen BIT = CAST(IIF(EXISTS(SELECT TOP 1 1 FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status' AND [Value] <> '0'), 1, 0) AS BIT);
	DECLARE @obModuleGUID UNIQUEIDENTIFIER = '65770F68-4223-43FE-970A-D7F8D8D3931D';

	DECLARE @rosterBudgetingCategoryGUID UNIQUEIDENTIFIER = 'DD9DE9F8-01AF-41BE-9144-4CAD060B6E64';
	DECLARE @budgetConfigurationCategoryGUID UNIQUEIDENTIFIER = '8EF0D151-FCD6-4D0F-925A-94548AF39102';
	DECLARE @featuresCategoryGUID UNIQUEIDENTIFIER = '4F18E245-FB8A-4390-AC5B-B6829543A66B';
	
	DECLARE @obLocalAdminGroupGUID UNIQUEIDENTIFIER = 'F515898A-9D76-4E68-896B-22AF1AA4CB72';
	DECLARE @systemCenterMenuItemGUID UNIQUEIDENTIFIER = 'D8C2EEB8-9039-4EC6-81B9-77ABA1F87E01';
	DECLARE @systemGeneratedStatisticsGuid UNIQUEIDENTIFIER = 'F1161287-169C-41BD-B548-0A7A6414D24D';
	

	-- Hide all ob sections except 'BeginBudgetPreparation', 'CloseBudget' and categories 'Budget Configurations', 'Roster Budgeting', 'Features'
	UPDATE permission 
	SET ReadValue = @isBudgetOpen, WriteValue = @isBudgetOpen
	FROM [dbo].[S3SimplePermission] permission
	INNER JOIN [dbo].[SystemCenterSection] section ON section.SectionGUID = permission.LootID
	INNER JOIN [dbo].[SystemCenterCategory] category ON category.CategoryGUID = section.CategoryGUID
	WHERE category.ModuleGUID = @obModuleGUID
	AND category.IsMaintenanceMode = 1
	AND section.GlobalID NOT IN ('BeginBudgetPreparation', 'CloseBudget')
	AND category.CategoryGUID NOT IN (@rosterBudgetingCategoryGUID, @budgetConfigurationCategoryGUID, @featuresCategoryGUID)
	
	--verify and update access for menu item system center button for users from OB Local Admin Group
	 IF EXISTS(SELECT * FROM S3SimplePermission WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID)	
	 BEGIN
		IF EXISTS(SELECT * FROM S3SimplePermission WHERE LootID IN (@systemGeneratedStatisticsGuid) and IdentityGUID = @obLocalAdminGroupGUID)			
			UPDATE [dbo].[S3SimplePermission]
			SET ReadValue = 1, WriteValue = 1
			WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID
		ELSE
			-- Hide menu item system center button if OB Local Admin didn't have access for 'Role Assignments' or 'System Generated Statistics' sections
			UPDATE [dbo].[S3SimplePermission]
			SET ReadValue = @isBudgetOpen, WriteValue = @isBudgetOpen
			WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID
	END	
END
GO


---------------------------------------------

---------------------------------------------
--  FUNCTIONS
---------------------------------------------

